python实现马耳可夫链算法

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

import random
import sys

MAXGEN = 10000
NONWORD = '\n'
w1 = w2 = NONWORD

statetab = {}
text = sys.stdin.read()
words = text.split()
for word in words:
    statetab.setdefault((w1, w2),[]).append(word)
    w1, w2 = w2, word

# add tail
statetab.setdefault((w1, w2),[]).append(NONWORD)

# show mar words
w1 = w2 = NONWORD
for i in xrange(MAXGEN):
    suf = statetab[(w1,w2)]
    t = random.choice(suf)
    if t == NONWORD:
    break
    print t
    w1, w2 = w2, t