Python 形態素解析エンジンMeCaBを使ってTwitterの分析
形態素解析は簡単にいうと文を名詞、動詞などの品詞分類をコンピュータを使って行うことをいいます。
そのソフトのひとつがMeCaBです。
ググると導入方法がたくさんでてきますが、時々刻々環境が変わり、その度うまくいかない報告が出ているようです。
僕も苦心しましたが、試しにapt-getしたら、現時点では対応していました。メモしておきます。
sudo apt-get install mecab-ipadic-utf8 mecab-jumandic-utf8
でMeCaB自体のインストール。
sudo pip install python-mecab
TwitterからTweetを取得して、品詞分類するようなプログラムを実行してみます。
TwitterのAPIを取得することと、
sudo pip install twitter
が必要です。
#coding:utf-8 import twitter import json import MeCab MECAB_MODE = 'mecabrc' PARSE_TEXT_ENCODING = 'utf-8' CONSUMER_KEY="" CONSUMER_SECRET="" ACCESS_TOKEN="" ACCESS_TOKEN_SECRET="" def parse(unicode_string): tagger = MeCab.Tagger(MECAB_MODE) text = unicode_string.encode(PARSE_TEXT_ENCODING) node = tagger.parseToNode(text) words = [] nouns = [] verbs = [] adjs = [] while node: pos = node.feature.split(",")[0] word = node.surface.decode("utf-8") if pos == "名詞": nouns.append(word) elif pos == "動詞": verbs.append(word) elif pos == "形容詞": adjs.append(word) words.append(word) node = node.next parsed_words_dict = { "all": words[1:-1], "nouns": nouns, "verbs": verbs, "adjs": adjs } return parsed_words_dict auth=twitter.OAuth(ACCESS_TOKEN,ACCESS_TOKEN_SECRET,CONSUMER_KEY,CONSUMER_SECRET) twitter_stream=twitter.TwitterStream(auth=auth,domain="userstream.twitter.com") for msg in twitter_stream.user(): if "text" in msg: tweet = msg["text"] words_dict= parse(tweet) print "All:", ",".join(words_dict['all']) print "Nouns:", ",".join(words_dict['nouns']) print "Verbs:", ",".join(words_dict['verbs']) print "Adjs:", ",".join(words_dict['adjs']) print "========END========"
実行結果は次のようになります。
All: いじわる,する,人,は,きらい,だ,ぬん Nouns: いじわる,人,きらい Verbs: する,ぬん Adjs: ========END======== All: 俺,も,頑張ろ,う Nouns: 俺 Verbs: 頑張ろ Adjs: ========END========
うーん、微妙に間違えてはいるものの、機械にしては頑張っているのではないでしょうか。
恐らく理屈的に名詞の抽出の正確性は高いので、「地震」とか「飯」とか特定のワードに対して統計処理を行うならば、それなりに妥当かもしれませんが。