LoginSignup
230

More than 5 years have passed since last update.

Python3からMeCabを使う

Last updated at Posted at 2016-04-30

日本語の形態素解析エンジン"MeCab"をMacにインストールしてPython3から利用する方法をまとめました。

MeCabと辞書をインストール

まずHomebrewでMeCabと辞書をインストールします。

$ brew install mecab
$ brew install mecab-ipadic

mecab-ipadic-NEologdをインストール

mecab-ipadic-NEologdをインストールします。
これはWeb上の新語をデフォルトの辞書に追加したものです。
必須ではありませんが便利なので入れておきます。
以下のコマンドでインストールできます。
詳しくはGitHubページをみてください。

$ brew install git curl xz
$ git clone --depth 1 git@github.com:neologd/mecab-ipadic-neologd.git
$ cd mecab-ipadic-neologd
$ ./bin/install-mecab-ipadic-neologd -n

mecab-python3をインストール

次にpipでmecab-python3をインストールします。

$ brew install swig
$ pip install mecab-python3

追記(2018/11/27)
コメントで『「unable to execute 'swig': No such file or directory」となりエラー終了する』との指摘をいただいたので修正しました

これで、Python3からMeCabが使えるようになりました。
以下に、サンプルコードを載せておきます。
MeCab.Taggerで指定するパスは

$ echo `mecab-config --dicdir`"/mecab-ipadic-neologd"

で調べられます。

import MeCab

mecab = MeCab.Tagger ('-d /usr/local/lib/mecab/dic/mecab-ipadic-neologd')

text = '解析したいテキスト'
mecab.parse('')#文字列がGCされるのを防ぐ
node = mecab.parseToNode(text)
while node:
    #単語を取得
    word = node.surface
    #品詞を取得
    pos = node.feature.split(",")[1]
    print('{0} , {1}'.format(word, pos))
    #次の単語に進める
    node = node.next

出力結果

 , *
解析 , サ変接続
し , 自立
たい , *
テキスト , 一般
 , *

参考

https://github.com/neologd/mecab-ipadic-neologd
http://shogo82148.github.io/blog/2015/12/20/mecab-in-python3-final/

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
230