はてなキーワードしりとりを改造・その5
前回書きなおした例外処理ですが、せっかく専用の例外クラスを作成したにも拘らずどの例外が発生したかを判別する処理がクラスの外(main関数)にあるという本末転倒になっていたので再度書きなおしました。
自分でもどうもしっくりこないと思いながら書いてはいたのですがコメントで教えていただいてやっと例外をクラスにする意義が分かりました(^_^;)
main関数がかなりすっきりして見易くなったのもうれしいです。
# 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 ShiritoriRuleError(u"UniquenessError", 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): """しりとりのルールに関連する処理を担う""" def __init__(self, furigana): if furigana is None: raise ShiritoriRuleError(u"DataNotFound") elif furigana is False: raise ShiritoriRuleError(u"XMLError") else: unicode.__init__(self, furigana) def exam(self, initial): """最初の文字と最後の文字を調べて適格か否か判断""" if not self.startswith(initial): raise ShiritoriRuleError(u"ILError", initial) if self.endswith(u"ん"): raise CrtShiritoriError() def creatIL(self): """次の単語用の「次の文字」を作成する""" toReplace = {u"ゃ":u"や", u"ゅ":u"ゆ", u"ょ":u"よ", u"を":u"お", u"っ":u"つ" , u"ぁ":u"あ", u"ぃ":u"い", u"ぅ":u"う", u"ぇ":u"え", u"ぉ":u"お"} if self.endswith(u"ー"): nextIL = self[-2:-1] else: nextIL = self[-1:] if nextIL in toReplace: nextIL = toReplace[nextIL] return nextIL class ShiritoriRuleError(Exception): """しりとりのルール違反を受け取る""" def __init__(self, kind=None, value=None): self.kind = kind self.value = value def __str__(self): if self.kind == u"UniquenessError": return u"この単語は" + str(self.value) + u"番目に使いました。" elif self.kind == u"DataNotFound": return u"この単語ははてなキーワードに登録されていませんでした。" elif self.kind == u"XMLError": return u"xmlデータを正しく受信できませんでした。他の単語を試してください。" elif self.kind == u"ILError": return u"次の文字は「" + str(self.value) + u"」です!" class CrtShiritoriError(ShiritoriRuleError): """発生した場合ループを抜ける例外""" def __str__(self): return u"「ん」がついたよ" def main(): furiganadict = HatenaFuriganaDict() # API問い合わせた単語をキー読み仮名を値として管理する usedwords = {} # 正答の単語をキー、何番目に使ったかを値として管理する initial = u"あ" #しりとりの最初の文字 print (u"最初のもじは「" + initial + u"」です") while True: try: wordU = input_reader(usedwords) furigana = Furigana(furiganadict[wordU]) furigana.exam(initial) except ShiritoriRuleError as e: print e continue except CrtShiritoriError as e: print e break print wordU initial = furigana.creatIL() usedwords[wordU] = len(usedwords) + 1 print u"終了です" if __name__ == "__main__": main()