[PYTHON] Use MeCab to fetch readings

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

Use MeCab to fetch readings
How to use mecab, neologd-ipadic on colab
How to use xml.etree.ElementTree
How to use Python-shell
How to use tf.data
How to use Seaboan
How to use image-match
How to use shogun
How to use Pandas 2
How to use Virtualenv
How to use numpy.vectorize
How to use pytest_report_header
Easy to use Flask
Use mecab with Python3
How to use partial
How to use Bio.Phylo
How to use SymPy
How to use x-means
How to use WikiExtractor.py
How to use IPython
How to use virtualenv
How to use Matplotlib
How to use iptables
How to use numpy
Reasons to use logarithm
How to use TokyoTechFes2015
How to use venv
How to use dictionary {}
How to use Pyenv
Easy to use SQLite3
How to use list []
How to use python-kabusapi
Python-How to use pyinstaller
How to use OptParse
How to use return
How to use dotenv
How to use pyenv-virtualenv
How to use Go.mod
How to use imutils
How to use import
How to use Qt Designer
How to use search sorted
[gensim] How to use Doc2Vec
python3: How to use bottle (2)
Understand how to use django-filter
How to use the generator
[Python] How to use list 1
Add a dictionary to MeCab
QSM analysis-How to use MEDI-
How to use FastAPI ③ OpenAPI
Use MeCab to translate sloppy sentences in a "slow" way.
How to use Python argparse
How to use IPython Notebook
How to use Pandas Rolling
[Note] How to use virtualenv
How to use redis-py Dictionaries
Python: How to use pydub
[Python] How to use checkio
Use Python's MeCab binding natto-py
[Go] How to use "... (3 periods)"
How to use Django's GeoIp2