我一直在研究這個代碼來生成隨機文本:Python代碼的解釋
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))
但是我無法理解的最後一位,從目標= randrange(SUM(d.values()))起。 解釋將不勝感激!謝謝!
非常感謝你,我現在明白了。但最後一點呢,是不是累積>目標總是如此?這個聲明的目的是什麼?謝謝你的幫助! – Julia 2012-01-01 21:41:32
我想知道如果「curr不在模型中:curr = choice(list(model))」必須替換爲「while curr not in model:curr = choice(list(model))」? (我已經在這段代碼上提過這個評論一次,但我有o答案) – jimifiki 2012-01-01 21:57:10
@jimifiki我不知道也許mlefavor呢。 – Julia 2012-01-01 22:01:02