Skip to content

Instantly share code, notes, and snippets.

@msmoode
Last active August 29, 2015 14:24
Show Gist options
  • Save msmoode/f3fbf4b00f36340cd511 to your computer and use it in GitHub Desktop.
Save msmoode/f3fbf4b00f36340cd511 to your computer and use it in GitHub Desktop.
Markov Chain
import random
nonWord = "\n"
class Chain:
words = {}
def __init__(self, data=None, base=None):
if data != None:
self.scan(data)
if base != None:
self.words = base
def scan(self, data):
w1 = None
w2 = None
for word in data.split(" "):
self.words.setdefault((w2, w1), []).append(word)
w2, w1 = w1, word
self.words.setdefault((w2, w1), []).append(nonWord)
def generate(self, max_words=80):
w1 = None
w2 = None
out = ""
for i in range(max_words):
word = random.choice(self.words[(w1,w2)])
if word == nonWord:
break
out += word + " "
w1 , w2 = w2, word
return out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment