日本語漢字から読み仮名変換

まずはjanomeのインストール

ailaby.com

その後、以下のコードを実行すればtxtファイルを 漢字, その読み(例: 「金閣寺, キンカクジ」)と変換できる。

# coding:utf-8
import os
import sys
import codecs
import tempfile
import shutil
import signal

try:
    from janome.tokenizer import Tokenizer
except Exception as e1:
    print e1, '\nplease install janome!'
    sys.exit(1)


class SignalException(Exception):
    def __init__(self, message):
        super(SignalException, self).__init__(message)


def do_exit(sig, stack):
    raise SignalException("Exiting")


# 変換
def translation(word):
    t = Tokenizer()
    tokens = t.tokenize(word)
    word_list = []
    for token in tokens:
        if token.reading == '*':
            word_list.append(token.surface)
        else:
            word_list.append(token.reading)
    return ", ".join([word, "".join(word_list)])


# ファイル読み
def read_file(input_file):
    with codecs.open(input_file, mode='r', encoding='utf-8') as f:
        while 1:
            line = f.readline()
            if line.strip() == "":
                break
            yield line.strip()

# ファイル読みからの変換の連携
def kanji2yomi(input_file):
    for word in read_file(input_file):
        dogigo = translation(word)
        ans = dogigo.split(', ')
        if ans[0] != ans[1]:
            yield dogigo


# ファイルの書き込み
def write_file(iterable, output_filename,):
    with tempfile.NamedTemporaryFile(delete=False, dir='/var/tmp') as f:
        for row in iterable:
            f.write((row + u'\n').encode('utf-8'))
        f.seek(0)
        shutil.move(f.name, output_filename)
    if os.path.exists(f.name):
        os.remove(f.name)


# 実行関数
def main():
    # import pdb;pdb.set_trace()
    input_f = '/vagrant/work/kanji.txt'
    output_f = '/vagrant/work/yomi.dat'
    signal.signal(signal.SIGINT, do_exit)
    signal.signal(signal.SIGHUP, do_exit)
    signal.signal(signal.SIGTERM, do_exit)
    try:
        write_file(kanji2yomi(input_f), output_f)
    except SignalException as e1:
        print e1
        sys.exit(1)


if __name__ == '__main__':
    main()