mojimoji 半角⇔全角の変換

mojimoji

自然言語処理の前処理として全半角の変換を行うことが多いと思いますが、その際に便利なmojimojiというライブラリについて学習します。全半角処理ができるライブラリは色々あるのですが、その中でもmojimojiは処理が比較的高速である点に特徴があります。

インストールは以下の通りpipで行います。一部のlinuxではgcc-c++がインストールがなくエラーが出るかもしれません。ページ下部の補足を参照してください。

pip install mojimoji

では使い方について見ていきましょう。

全角から半角へ変換する

その名もズバリzen_to_hanメソッドを使用します。kana、digit、asciiというオプションをキーワード引数で指定すると、カナ、数字、アルファベットの無効化を指定することができます。

import mojimoji

text = "python パイソン 1000"
print(mojimoji.zen_to_han(text)) # python パイソン 1000

print(mojimoji.zen_to_han(text, kana=False)) # python パイソン 1000

print(mojimoji.zen_to_han(text, digit=False)) # python パイソン 1000

print(mojimoji.zen_to_han(text, ascii=False)) # python パイソン 1000

特に解説は不要かと思います。形態素解析の前処理ではkana=Falseのみを指定するケースが多いのではないでしょうか。

半角から全角へ変換する

こちらの処理は使う機会があまりないかもしれませんが、参考のため掲載します。han_to_zenメソッドを使用します。やはりzen_to_hanと同様、kana、digit、asciiというオプションをキーワード引数で指定すると、カナ、数字、アルファベットの無効化を指定することができます。

import mojimoji

text = "python パイソン 1000"
print(mojimoji.han_to_zen(text)) # python パイソン 1000 

print(mojimoji.han_to_zen(text, kana=False)) # python パイソン 1000 

print(mojimoji.han_to_zen(text, digit=False)) # python パイソン 1000 

print(mojimoji.han_to_zen(text, ascii=False)) # python パイソン 1000 

インストールの補足

特定の環境ではgcc-c++が無いため以下のエラーが出力されます。

$ pip install mojimoji
Collecting mojimoji
  Downloading mojimoji-0.0.5.tar.gz
Installing collected packages: mojimoji
  Running setup.py install for mojimoji ... error
    Complete output from command /home/pyuser/.pyenv/versions/3.5.1/bin/python3.5 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-k3m9jq1j/mojimoji/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-dk8ayn4w-record/install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_ext
    building 'mojimoji' extension
    creating build
    creating build/temp.linux-x86_64-3.5
    gcc -pthread -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/pyuser/.pyenv/versions/3.5.1/include/python3.5m -c mojimoji.cpp -o build/temp.linux-x86_64-3.5/mojimoji.o
    gcc: error trying to exec 'cc1plus': execvp: No such file or directory
    error: command 'gcc' failed with exit status 1

    ----------------------------------------
Command "/home/pyuser/.pyenv/versions/3.5.1/bin/python3.5 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-k3m9jq1j/mojimoji/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-dk8ayn4w-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-k3m9jq1j/mojimoji/

以下のコマンドでgcc-c++をインストールして再度pipコマンドを実行してみてください。

yum install gcc-c++