Created
May 9, 2017 17:11
-
-
Save willismonroe/1a0e88715e292608356413b833e86c97 to your computer and use it in GitHub Desktop.
Simple Markov Chain in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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