I was addicted to installing python-mecab, so I just wanted to do what Pat read, so I decided to just hit the mecab command.
mecab can get the reading like this (it can not be taken unless it is in the dictionary)
$ echo "Apple" | mecab -Oyomi
Apple
So, here's a script that pulls the name from Django's model and converts it to Yomigana.
yomigana.py
# -*- coding: utf-8 -*-
import os
import sys
import re
from subprocess import Popen, PIPE
import jcconv
from django.conf import settings
sys.path.append(os.path.abspath(os.path.dirname('.')))
os.environ['DJANGO_SETTINGS_MODULE'] = 'hogehoge.settings'
from hogehoge.apps.fuga.models import Piyo
def get_yomigana(text):
p1 = Popen(['echo', text], stdout=PIPE)
p2 = Popen(['mecab', '-Oyomi'], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()
output = p2.communicate()[0]
return re.sub(r'\n', '', output)
for piyo in Piyo.objects.all():
yomigana = jcconv.kata2hira(jcconv.half2hira(get_yomigana(piyo.name )))
print ','.join([str(user.id), piyo.name.encode('cp932'), yomigana.decode('utf8').encode('cp932')])
The project name is hogehoge. I referred to the following manual for hitting external commands.
-17.1. Subprocess — Subprocess Management — Python 2.7ja1 documentation
Apparently, os.system is going to be abolished (2.7)
Recommended Posts