Skip to content

Instantly share code, notes, and snippets.

@bentrevett
Created November 18, 2017 00:34
Show Gist options
  • Save bentrevett/173ef4cfda50db4628b862513d239154 to your computer and use it in GitHub Desktop.
Save bentrevett/173ef4cfda50db4628b862513d239154 to your computer and use it in GitHub Desktop.
import re
from sys import stdout
from random import randint, choice
from collections import defaultdict
#http://theorangeduck.com/page/17-line-markov-chain
#http://theorangeduck.com/media/uploads/other_stuff/poetry.zip
with open('poetry.txt') as f:
words = re.split(' +', f.read())
transition = defaultdict(list)
for w0, w1, w2 in zip(words[0:], words[1:], words[2:]):
transition[w0, w1].append(w2)
i = randint(0, len(words)-3)
w0, w1, w2 = words[i:i+3]
for _ in range(500):
stdout.write(w2+' ')
w0, w1, w2 = w1, w2, choice(transition[w1, w2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment