我想使用 .txt 文件中的一本书中的字母频率生成随机文本,以便每个新字符 (string.lowercase + ' '
) 取决于前一个。
如何使用马尔可夫链来做到这一点?或者使用每个字母都有条件频率的 27 个数组更简单?
我想使用来自的字母频率生成随机文本
txt 文件中的书籍
考虑使用收藏.柜台 http://docs.python.org/library/collections.html#counter-objects一次循环文本文件两个字母时建立频率。
如何使用马尔可夫链来做到这一点?还是用27个数组更简单
每个字母的条件频率?
这两个语句是等价的。马尔可夫链是what你正在做的。具有条件频率的 27 个阵列是how你正在做。
以下是一些基于字典的代码,可以帮助您入门:
from collections import defaultdict, Counter
from itertools import ifilter
from random import choice, randrange
def pairwise(iterable):
it = iter(iterable)
last = next(it)
for curr in it:
yield last, curr
last = curr
valid = set('abcdefghijklmnopqrstuvwxyz ')
def valid_pair((last, curr)):
return last in valid and curr in valid
def make_markov(text):
markov = defaultdict(Counter)
lowercased = (c.lower() for c in text)
for p, q in ifilter(valid_pair, pairwise(lowercased)):
markov[p][q] += 1
return markov
def genrandom(model, n):
curr = choice(list(model))
for i in xrange(n):
yield curr
if curr not in model: # handle case where there is no known successor
curr = choice(list(model))
d = model[curr]
target = randrange(sum(d.values()))
cumulative = 0
for curr, cnt in d.items():
cumulative += cnt
if cumulative > target:
break
model = make_markov('The qui_.ck brown fox')
print ''.join(genrandom(model, 20))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)