Python Bigram formation from given list

In this post we will discuss about bigram formation from a given list in python programming language. We will discuss two methods for creating bigrams.

When we are dealing with text classification, sometimes we need to do certain kind of natural language processing and hence sometimes require to form bigrams of words for processing. In case of absence of appropriate library, its difficult and having to do the same is always quite useful. Let’s discuss certain ways in which this can be achieved.

Solution 1: Using list comprehension + enumerate() + split()

The combination of above three functions can be used to achieve this particular task. The enumerate function performs the possible iteration, split function is used to make pairs and list comprehension is used to combine the logic.

Python program for Bigram Formation from a given list:

test_list = ['proprogramming is best', 'I love it']

print ("The original list is : " + str(test_list))

res = [(x, i.split()[j + 1]) for i in test_list 

       for j, x in enumerate(i.split()) if j < len(i.split()) - 1]

print ("The formed bigrams are : " + str(res))
Output :
The original list is : [‘proprogramming is best’, ‘I love it’]

 The formed bigrams are : [(‘proprogramming’, ‘is’), (‘is’, ‘best’), (‘I’, ‘love’), (‘love’, ‘it’)]

Solution 2: Using zip() + split() + list comprehension

The task that enumerate performed in the above method can also be performed by the zip function by using the iterator and hence in a faster way. Let’s discuss certain ways in which this can be done.

test_list = ['proprogramming is best', 'I love it']

print ("The original list is : " + str(test_list))

res = [i for j in test_list 
       for i in zip(j.split(" ")[:-1], j.split(" ")[1:])]

 
print ("The formed bigrams are : " + str(res))
Output :
The original list is : [‘proprogramming is best’, ‘I love it’] 

The formed bigrams are : [(‘proprogramming’, ‘is’), (‘is’, ‘best’), (‘I’, ‘love’), (‘love’, ‘it’)]

Check other python programs here: Python Programs.

Leave a Comment