This blog post will explain how to generate random text from trigrams with python.
The random library has to be imported so the sentence generator can pick a random word. The defaultdict library has to be imported from collections to hold the trigram language model. The re library has to be imported for tokenization.
import random
from collections import defaultdict
import re
A sentence tokenizer function is created. A pattern will be defined. The variable sentences is made equal to the result of the re.split function. The return value of the function is a list of sentences.
def tokenizer(t):
pattern = r'(?<=\.|\?|!)\s'
sentences = re.split(pattern, t)
return sentences
A function that generates random text is created. Variables w1 and w2 will have the start words assigned to it. A list name output is declared and will hold the values of variables w1 and w2. A for loop will be used to create random text. The next_words_dict variable is assigned to the output of function model get. If no word is found, the loop will break. The variable next_word will hold a random word that is picked from the dictornary. That value is appended to the output list. The variables w1 and w2 are assigned to w2 and next_word. Once the loop is finished executing, the contents of the list output is returned by the function.
def generate_text(model, start_words, length):
w1, w2 = start_words
output = [w1, w2]
for _ in range(length - 2):
next_words_dict = model.get((w1, w2))
if not next_words_dict:
break
next_word = random.choices(
list(next_words_dict.keys()),
weights=next_words_dict.values()
)[0]
output.append(next_word)
w1, w2 = w2, next_word
return " ".join(output)
Example text used for the blog post is placed in the variable text.
text = """TextBlob is very amazing and simple to use.
What a great tool! That tool helps with simple tasks.
Tokenization is easy with that tool.
"""
The variable words is declared as a list.
words = []
The variable sentences is made equal to the result of the sentence tokenizer function.
sentences = tokenizer(text)
A for loop will strip punctuation from a sentence using a regular expression and lowercase each sentence.
for sentence in sentences:
words += re.sub(r'[^\w\s]', '', sentence).lower().split(' ')
A model is declared to hold the trigram language model.
model = defaultdict(dict)
A for loop will generate trigrams and build the trigram language model.
for i in range(len(words) - 2):
key = (words[i], words[i + 1])
next_word = words[i + 2]
if next_word in model[key]:
model[key][next_word] += 1
else:
model[key][next_word] = 1
Two starting words are declared as a tuple and stored in the variable start.
start = ("that","tool")
A function generates random text.
random_text = generate_text(model, start, 5)
The results of that function are printed onto the console.
print(random_text)
This is what the whole source code looks like.
import random
from collections import defaultdict
import re
def tokenizer(t):
pattern = r'(?<=\.|\?|!)\s'
sentences = re.split(pattern, t)
return sentences
def generate_text(model, start_words, length):
w1, w2 = start_words
output = [w1, w2]
for _ in range(length - 2):
next_words_dict = model.get((w1, w2))
if not next_words_dict:
break
next_word = random.choices(
list(next_words_dict.keys()),
weights=next_words_dict.values()
)[0]
output.append(next_word)
w1, w2 = w2, next_word
return " ".join(output)
text = """TextBlob is very amazing and simple to use.
What a great tool! That tool helps with simple tasks.
Tokenization is easy with that tool.
"""
words = []
sentences = tokenizer(text)
for sentence in sentences:
words += re.sub(r'[^\w\s]', '', sentence).lower().split(' ')
model = defaultdict(dict)
for i in range(len(words) - 2):
key = (words[i], words[i + 1])
next_word = words[i + 2]
if next_word in model[key]:
model[key][next_word] += 1
else:
model[key][next_word] = 1
start = ("that","tool")
random_text = generate_text(model, start, 5)
print(random_text)