Created
October 16, 2012 01:43
-
-
Save dtuominen/3896824 to your computer and use it in GitHub Desktop.
This file contains 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 | |
from pprint import pprint | |
from collections import defaultdict | |
def get_words(fname='fyad.txt'): | |
with open(fname) as f: | |
return f.read().split() | |
def triplets(words): | |
for i in xrange(len(words) - 2): | |
yield (words[i], words[i+1], words[i+2]) | |
def chain(words): | |
chains = defaultdict(list) | |
for w1, w2, w3 in triplets(words): | |
pair = (w1, w2) | |
chains[pair].append(w3) | |
return chains | |
def markov(chains, words): | |
w1, w2 = '\n', '\n' | |
output = [] | |
for word in range(len(words) - 2): | |
#first case | |
if '\n' in w1 and w2: | |
w1, w2 = words[0], words[1] | |
w3 = random.choice(chains[(w1, w2)]) | |
output.append(w3) | |
w1, w2 = w2, w3 | |
return output | |
if __name__ == '__main__': | |
words = get_words('fyad.txt') | |
chains = chain(words) | |
output = markov(chains, words) | |
print ' '.join(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment