はてなキーワードしりとりを改造・その7
その6のコードには昨日、一昨日の記事に書いていたイミュータブルな型の継承に関する間違いがあったのでそれを修正しました。
また例外が発生した際に従来は「この単語ははてなキーワードに登録されていませんでした。」というような表記だったのですが「『○○○』ははてなキーワードに登録されていませんでした。」のように具体的にどの単語なのかを表示するように変更しました。
# coding: utf-8 import urllib import urllib2 from xml.dom.minidom import parse def input_reader(usedwords): """入力を受け取ってunicodeオブジェクトにして返す""" word = raw_input(u"次の単語を入力してください。次は" + str(len(usedwords) + 1) + u"語目です。") wordU = unicode(word, "utf-8") if wordU in usedwords: raise UniquenessError(wordU, usedwords[wordU]) return wordU class HatenaFuriganaDict(dict): """入力された単語とそのふりがなの組み合わせを辞書として管理する はてなキーワードに登録されていなかった単語の値はNone APIから正しいxmlが受信できない単語の値はFalseとする """ @staticmethod def _ask_hatena(word): """__missing__から呼ばれてwordをはてなキーワードAPIに問い合わせる""" #URLエンコード encoded_word = urllib.quote(word.encode("utf-8")) #URLを作成 requestURL = ("http://search.hatena.ne.jp/keyword?word=" + encoded_word + "&mode=rss&ie=utf8&page=1") return urllib2.urlopen(requestURL, None) def __missing__(self, word): """この辞書に登録されていないwordが参照された場合に呼ばれ APIに問い合わせを行い返答する。さらにその結果を辞書に登録する """ try: dom = parse(self._ask_hatena(word)) except: self[word] = False return self[word] items = dom.getElementsByTagName("item") hatenaNS = "http://www.hatena.ne.jp/info/xmlns#" #XMLのNS if items and (items[0].getElementsByTagName("title"))[0].firstChild.data == word: self[word] = (items[0].getElementsByTagNameNS(hatenaNS, "furigana"))[0].firstChild.data else: self[word] = None return self[word] class Furigana(unicode): """しりとりのルールに関連する処理を担う""" # 語尾置換用文字列 rep_letters = {u"ゃ":u"や", u"ゅ":u"ゆ", u"ょ":u"よ", u"を":u"お", u"っ":u"つ" , u"ぁ":u"あ", u"ぃ":u"い", u"ぅ":u"う", u"ぇ":u"え", u"ぉ":u"お"} to_replace = {} # Unicodeコードポイントに置き換え for k, v in rep_letters.iteritems(): to_replace[ord(k)] = v def __new__(cls, furigana, word): if furigana is None: raise DataNotFoundError(word) elif furigana is False: raise XMLError(word) else: return unicode.__new__(cls, furigana) def exam(self, initial, word): """最初の文字と最後の文字を調べて適格か否か判断""" if not self.startswith(initial): raise ILError(word=word, value=initial) if self.endswith(u"ん"): raise CrtShiritoriError(word) def creatIL(self): """次の単語用の「次の文字」を作成する""" if self.endswith(u"ー"): nextIL = self[-2:-1] else: nextIL = self[-1:] nextIL = nextIL.translate(Furigana.to_replace) return nextIL class ShiritoriRuleError(Exception): """しりとりのルール基底クラス""" def __init__(self, word=u"この単語", value=None): self.word = u"「" + word + u"」" self.value = value class UniquenessError(ShiritoriRuleError): def __str__(self): return self.word + u"は" + str(self.value) + u"番目に使いました。" class DataNotFoundError(ShiritoriRuleError): def __str__(self): return self.word + u"ははてなキーワードに登録されていませんでした。" class XMLError(ShiritoriRuleError): def __str__(self): return self.word + u"のxmlデータを正しく受信できませんでした。他の単語を試してください。" class ILError(ShiritoriRuleError): def __str__(self): return self.word + u"は使えません。次の文字は「" + str(self.value) + u"」です!" class CrtShiritoriError(ShiritoriRuleError): """発生した場合ループを抜ける例外""" def __str__(self): return self.word + u"は「ん」で終わっています。" def main(): furiganadict = HatenaFuriganaDict() # API問い合わせた単語をキー読み仮名を値として管理する usedwords = {} # 正答の単語をキー、何番目に使ったかを値として管理する initial = u"は" #しりとりの最初の文字 print (u"最初のもじは「" + initial + u"」です") while True: try: wordU = input_reader(usedwords) furigana = Furigana(furiganadict[wordU], wordU) furigana.exam(initial, wordU) except CrtShiritoriError ,e: print e break except ShiritoriRuleError ,e: print e continue print wordU initial = furigana.creatIL() usedwords[wordU] = len(usedwords) + 1 print u"終了です" if __name__ == "__main__": main()