https://shimi-dai.com/python-markov/から拝借した以下のプログラムですが,
テーブル作成時のプログラムがどのように動いて,どのようなテーブルが作成されているのかご教授お願いします。
以下のような認識であっているでしょうか?
wordlistが["A","B","C","D","E","F"]ならば,
[(A, B):C, (B, C):D, (C, D):E, (D, E):F]
のように連続する3要素を関連性の深い組み合わせとして,
tmp = random.choice(markov[(w1, w2)])で
(A, B):Cならば,AとBのいずれかとCをペアとしてsentenceに加える。
python3
1# -*- coding: utf-8 -*- 2import random 3import MeCab 4 5# MeCab使用してテキストデータを単語に分割する 6def wakati(text): 7 t = MeCab.Tagger("-Owakati") 8 m = t.parse(text) 9 result = m.rstrip(" \n").split(" ") 10 return result 11 12if __name__ == "__main__": 13 filename = "test.txt" 14 src = open(filename, "r").read() 15 wordlist = wakati(src) 16 17 # マルコフ連鎖用のテーブルを作成する 18 markov = {} 19 w1 = "" 20 w2 = "" 21 for word in wordlist: 22 if w1 and w2: 23 if (w1, w2) not in markov: 24 markov[(w1, w2)] = [] 25 #print('w1 not in markov ', w1) 26 #print('w2 not in markov ', w2) 27 markov[(w1, w2)].append(word) 28 #print('w1 append:', w1) 29 #print('w2 append:', w2) 30 w1, w2 = w2, word 31 #print('w1:', w1) 32 #print('w2:', w2) 33 34 # 文章の自動作成 35 count = 0 36 sentence = "" 37 w1, w2 = random.choice(list(markov.keys())) 38 while count < len(wordlist): 39 tmp = random.choice(markov[(w1, w2)]) 40 sentence += tmp 41 w1, w2 = w2, tmp 42 count += 1 43 44 print(sentence)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/11/27 00:04 編集
2018/11/27 00:32
2018/11/27 02:56