Skip to content

Instantly share code, notes, and snippets.

@mohdsanadzakirizvi
Last active November 6, 2019 09:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mohdsanadzakirizvi/4dc46480f009644f240eb8e162d3b23e to your computer and use it in GitHub Desktop.
Save mohdsanadzakirizvi/4dc46480f009644f240eb8e162d3b23e to your computer and use it in GitHub Desktop.
# code courtesy of https://nlpforhackers.io/language-models/
import random
# starting words
text = ["today", "the"]
sentence_finished = False
while not sentence_finished:
# select a random probability threshold
r = random.random()
accumulator = .0
for word in model[tuple(text[-2:])].keys():
accumulator += model[tuple(text[-2:])][word]
# select words that are above the probability threshold
if accumulator >= r:
text.append(word)
break
if text[-2:] == [None, None]:
sentence_finished = True
print (' '.join([t for t in text if t]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment