Skip to content

Instantly share code, notes, and snippets.

@ikegami-yukino
Last active May 15, 2018 16:11
Show Gist options
  • Save ikegami-yukino/5474642 to your computer and use it in GitHub Desktop.
Save ikegami-yukino/5474642 to your computer and use it in GitHub Desktop.
MeCabで日本語の回文判定
# -*- 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