Last active
May 15, 2018 16:11
-
-
Save ikegami-yukino/5474642 to your computer and use it in GitHub Desktop.
MeCabで日本語の回文判定
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import MeCab | |
mecab_y = MeCab.Tagger("-Oyomi") | |
def toYomi(text): | |
return mecab_y.parse(text).rstrip().replace(' ', '') | |
def normalize(text): | |
text = text.replace('ファ', 'ハ') | |
text = text.replace('フォ', 'ホ') | |
text = text.replace('ヲ', 'オ') | |
text = text.replace('アー', 'アア') | |
text = text.replace('イー', 'イイ') | |
text = text.replace('ウー', 'ウウ') | |
text = text.replace('エー', 'エエ') | |
text = text.replace('オー', 'オオ') | |
return text | |
def is_palindrome(text): | |
yomi = toYomi(text) | |
yomi = normalize(yomi) | |
length = len(yomi) | |
if length < 2: # 2文字以下は回文 | |
return True | |
elif length % 2 == 0: | |
return yomi[:length/2] == yomi[:length/2-1:-1] | |
return yomi[:length/2] == yomi[:length/2:-1] | |
if __name__ == '__main__': | |
while True: | |
print is_palindrome(input('>').decode('utf8', 'replace')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment