This blog post will explain how to generate trigrams from text with python.
The trigrams are generated using a for loop. The variable trigrams 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 two. This is done so the append function can extract the trigrams from the list tokens. Once the last trigram is extracted from the list tokens, the loop terminates.
def tgrams(tokens):
trigrams = []
for i in range(len(tokens) - 2):
trigrams.append((tokens[i], tokens[i + 1], tokens[i + 2]))
return trigrams
The variable text will hold that string that is going to be processed into trigrams.
text = "The cat sat on a mat"
The text is lowercased and split into a list of tokens or words.
tokens = text.lower().split(' ')
The tgrams function is feed with a list of tokens that will be processed into trigrams.
r = tgrams(tokens)
The trigrams are printed onto the screen.
print(r)
This is what the whole source code looks like.
def tgrams(tokens):
trigrams = []
for i in range(len(tokens) - 2):
trigrams.append((tokens[i], tokens[i + 1], tokens[i + 2]))
return trigrams
text = "The cat sat on a mat"
tokens = text.lower().split(' ')
r = tgrams(tokens)
print(r)