[作り方を徹底解説] 人工知能が書いたAI入門ブログ
を参考に、janome・マルコフ連鎖を用いたプログラムを作成しました。
下記ソースコードをpython3.6.4 Anaconda + windows環境で実行したところ、
Traceback (most recent call last): File "PlayingJanome.py", line 53, in <module> s = make_sentence(dic) File "PlayingJanome.py", line 41, in make_sentence w1 = word_choice(top) NameError: name 'word_choice' is not defined
とのエラーが発生し、最後までプログラムを実行することができませんでした。
(辞書ファイルのmarkov-blog.jsonは生成されています)
考えうるエラーの発生原因や、解決方法を教えていただければ幸いです。
#ソースコード
python
1# -*- coding: utf-8 -*- 2 3from janome.tokenizer import Tokenizer 4import os, re, json, random 5 6t = Tokenizer() 7words = t.tokenize(u'一本でも人参。二足でもサンダル。三艘でもヨット。四粒でもごま塩。五台でもロケット。') 8 9# 辞書を生成します 10def make_dic(words): 11 tmp = ["@"] 12 dic = {} 13 for i in words: 14 word = i.surface 15 if word == "" or word == "\r\n" or word == "\n": continue 16 tmp.append(word) 17 if len(tmp) < 3: continue 18 if len(tmp) > 3: tmp = tmp[1:] 19 set_word3(dic, tmp) 20 if word == "。": 21 tmp = ["@"] 22 continue 23 return dic 24 25# 三要素のリストを辞書として登録しています 26def set_word3(dic, s3): 27 w1, w2, w3 = s3 28 if not w1 in dic: dic[w1] = {} 29 if not w2 in dic[w1]: dic[w1][w2] = {} 30 if not w3 in dic[w1][w2]: dic[w1][w2][w3] = 0 31 dic[w1][w2][w3] += 1 32 33dic = make_dic(words) 34json.dump(dic, open("markov-blog.json", "w", encoding="utf-8")) 35 36# 記事を作文します 37def make_sentence(dic): 38 ret = [] 39 if not "@" in dic: return "no dic" 40 top = dic["@"] 41 w1 = word_choice(top) 42 w2 = word_choice(top[w1]) 43 ret.append(w1) 44 ret.append(w2) 45 while True: 46 w3 = word_choice(dic[w1][w2]) 47 ret.append(w3) 48 if w3 == "。": break 49 w1, w2 = w2, w3 50 return "".join(ret) 51 52for i in range(20): 53 s = make_sentence(dic) 54 print(s)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/02/23 08:43