.txtファイルの本から文字の頻度を使用してランダムなテキストを生成したいので、新しい文字(string.lowercase + ' '
)はそれぞれ前の文字に依存します。
マルコフ連鎖を使用してこれを行うにはどうすればよいですか?または、各文字に条件付き頻度で27個の配列を使用する方が簡単ですか?
.txtファイルの本から文字の頻度を使用してランダムなテキストを生成したいので、新しい文字(string.lowercase + ' '
)はそれぞれ前の文字に依存します。
マルコフ連鎖を使用してこれを行うにはどうすればよいですか?または、各文字に条件付き頻度で27個の配列を使用する方が簡単ですか?
txtファイルの本から文字の頻度を使用してランダムなテキストを生成したい
一度に2文字ずつテキストファイルをループする場合は、collections.Counterを使用して頻度を増やすことを検討してください。
マルコフ連鎖を使用してこれを行うにはどうすればよいですか?または、各文字に条件付き頻度で27個の配列を使用する方が簡単ですか?
2つのステートメントは同等です。マルコフ連鎖はあなたがしていることです。条件付き頻度の27の配列は、それを実行する方法です。
始めるための辞書ベースのコードは次のとおりです。
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))
各文字が前の文字のみに依存している場合は、27^2の文字ペアすべての確率を計算できます。