The blog post will explain how to generate bigrams from text with python.
The regular expressions library has to be loaded. This is done so that a regular expression can be used to eliminate punctuation from a string.
import re
Then a string variable is declared. This is the string that is going to be tokenized.
s = "How is it going today?"
The variable tokens will hold the result of the re.sub function with the functions lower and split appended to it. The re.sub function will strip a string of all punctuation marks. The lower function will turn all characters in the string to lowercase. The split function will convert the string into a list of tokens or words using a space as a delimiter.
tokens = re.sub(r'[^\w\s]', '', s).lower().split(' ')
The bigrams are generated using a for loop. The variable bigrams is assigned to an empty list. The loop starts at 1, and the range function will be assigned the length of the tokens list minus one. This is done so the append function can extract the bigrams from the list tokens. Once the last bigram is extracted from the list tokens, the loop terminates.
bigrams = []
for i in range(len(tokens) - 1):
bigrams.append((tokens[i], tokens[i + 1]))
The bigrams are printed onto the screen.
print(bigrams)
This is what the whole source code looks like.
import re
s = "How is it going today?"
tokens = re.sub(r'[^\w\s]', '', s).lower().split(' ')
bigrams = []
for i in range(len(tokens) - 1):
bigrams.append((tokens[i], tokens[i + 1]))
print(bigrams)