Skip to content

Instantly share code, notes, and snippets.

@willismonroe
Created May 9, 2017 17:11
Show Gist options
  • Save willismonroe/1a0e88715e292608356413b833e86c97 to your computer and use it in GitHub Desktop.
Save willismonroe/1a0e88715e292608356413b833e86c97 to your computer and use it in GitHub Desktop.
Simple Markov Chain in Python
import random
def markov(string, length):
list_of_tokens = string.split()
markov_dict = {}
prev = None
for token in list_of_tokens:
if prev is not None:
if prev in markov_dict.keys():
markov_dict[prev].append(token)
else:
markov_dict[prev] = [token]
prev = token
token = random.choice(list(markov_dict.keys()))
new_text = [token]
for i in range(length-1):
if token in markov_dict.keys():
choice = random.choice(markov_dict[token])
else:
token = random.choice(list(markov_dict.keys()))
choice = random.choice(markov_dict[token])
new_text.append(choice)
token = choice
return markov_dict, ' '.join(new_text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment