LoginSignup
38
36

More than 3 years have passed since last update.

MeCabを使って、テキスト中に含まれる品詞をカウントしてみよう!

Last updated at Posted at 2017-12-14

概要

このエントリは、自然言語処理の基礎を学ぶためのものです。
画像処理では画像を扱い、音声処理では音を扱いますが、自然言語処理ではテキストが対象となります。
テキストをコンピュータで処理していきたいのですが、その前段階としてテキストを部分ごとに区切らなければいけません。
テキストを部分ごとに区切る作業を形態素解析といい、それをするためにはMeCabという形態素解析エンジンを使います。
今回はMeCabを触ってみたいと思います。

インストール

Mecab のインストールにはこちらをご参考ください

MeCabで遊んでみる

parseToNode()というメソッドで、最初のnodeを取得します。
node.nextをすることによって次のnodeに移ることができます。
nodeのsurfaceには語が、featureには特徴が入っています。
例えば、バナナという単語であれば以下のようになります。
node.surface = "バナナ"
node.feature = "名詞,一般,*,*,*,*,バナナ,バナナ,バナナ"

mecab_test.py
import MeCab

text = "私はバナナが好きです。"

mecabTagger = MeCab.Tagger("-Ochasen")
node = mecabTagger.parseToNode(text)
while node:
    word = node.surface
    hinshi = node.feature.split(",")[0]
    print(word+": "+hinshi)
    node = node.next
私: 名詞
は: 助詞
バナナ: 名詞
が: 助詞
好き: 名詞
です: 助動詞
。: 記号

MeCabで品詞をカウントする

node.feature中の1番左の部分に品詞の情報が格納されています。
辞書型のデータ構造をうまく使い、品詞をカウントしていきましょう。

mecab_hinshi_test.py
# coding: utf-8
import MeCab

text = "私の好きな果物はバナナです。"

mecabTagger = MeCab.Tagger("-Ochasen")
node = mecabTagger.parseToNode(text)
hcount = {}
while node:
    hinshi = node.feature.split(",")[0]
    if hinshi in hcount.keys():
        freq = hcount[hinshi]
        hcount[hinshi] = freq + 1
    else:
        hcount[hinshi] = 1
    node = node.next
for key,value in hcount.items():
    print(key+":"+str(value))
名詞:4
助詞:2
記号:1
助動詞:2
38
36
1

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
38
36