Write a Python Program That Produces a Bigram Feature Vector From a Given String

Bi gram  feature vector is defined as A pair of consecutive written units such as words. Given a string as a input to the Python program your task is to get the bi gram feature vector of given  input string.

 

 

Write a Python Program That Produces a Bigram Feature Vector From a Given String

 


For example let's take a below string to find the bi gram vector

string = "sun rises in the east"

The bi gram feature vector  for the above string is shown below

Bi gram Feature Vector = [('sun', 'rises'), ('rises', 'in'), ('in', 'the'), ('the', 'east')]




Write a Python Program That Produces a Bigram Feature Vector From a Given String

Let’s ask users to enter a string by taking a string variable text.  at the same time state the input text into a list of strings using the split function call.

text = input("Enter a String : ").split(" ")




Take an empty list  variable named as bigram_list, Use the for loop to iterate all the  items present in the list  of strings .

Take two lists and  zip together the first list  should not contain the last item and the  second should not contain the first item.  append the zipped element that is bigram to the list

bigram_list = []
for bigram in zip(text[:-1], text[1:]):
    bigram_list.append(bigram)




Once the for loop is complete,  print the bi gram list  using the print function call.

print(bigram_list)





complete program
=======================

text = input("Enter a String : ").split(" ")

bigram_list = []
for bigram in zip(text[:-1], text[1:]):
    bigram_list.append(bigram)

print(bigram_list)





Output
==============

Enter a String : Write a Python Program That Produces a Bigram Feature Vector From a Given String


[('Write', 'a'), ('a', 'Python'), ('Python', 'Program'), ('Program', 'That'), ('That', 'Produces'), ('Produces', 'a'), ('a', 'Bigram'), ('Bigram', 'Feature'), ('Feature', 'Vector'), ('Vector', 'From'), ('From', 'a'), ('a', 'Given'), ('Given', 'String')]





Output 2
=================

Enter a String : bigram feature vector 


[('bigram', 'feature'), ('feature', 'vector')]





Conclusion
==================

Execute the above program by providing a random string as an input to the Python program for down the results.

Comment it  down  below if you have any queries or suggestions on the above program


Post a Comment

0 Comments