Skip to content

Instantly share code, notes, and snippets.

@kragen
Created December 17, 2008 03:38
Show Gist options
  • Save kragen/36926 to your computer and use it in GitHub Desktop.
Save kragen/36926 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
"Second-order Markov-chain text generator."
import sys, random
def words(infile):
for line in infile:
for word in line.split(): yield intern(word)
freqs = {}
state = [None, None]
for word in words(sys.stdin):
freqs.setdefault(tuple(state), []).append(word)
state.append(word)
state.pop(0)
for _ in xrange(1000):
if tuple(state) not in freqs: state = [None, None]
word = random.choice(freqs[tuple(state)])
print word,
state.append(word)
state.pop(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment