ubuntu & pythonで形態素解析
pythonなどのお勉強のためにやってみた。
お題
「Googleが今まで立ち上げてきたプロジェクト(検索、ブックサーチ、YouTube買収、Googleアース、ストリートビューなど)の舞台裏が書かれていて興味深かった。」
を解析し、名詞をリストアップ。
Yahoo!の形態素解析サービス
http://d.hatena.ne.jp/aidiary/20090415/1239802199
をパクらせて頂きました。
ローカルMeCab(IPA辞書)で形態素解析
$ sudo apt-get install mecab-ipadic-utf8 mecab python-mecab
[main.py]
#!/usr/bin/env python # -*- coding: utf-8 -*- from timeit import Timer from japanese import get_nouns sentence = u"Googleが今まで立ち上げてきたプロジェクト(検索、ブックサーチ、YouTube買収、Googleアース、ストリートビューなど)の舞台裏が書かれていて興味深かった。".encode("utf-8") def f(): for w in get_nouns(sentence): print w, print t = Timer("f()", "from __main__ import f") print t.timeit(number=10) / 10
[japanese.py]
# -*- coding: utf-8 -*- ''' 日本語関連モジュール ''' import MeCab import re MEISHI = u"名詞".encode("utf-8") __mecab__ = MeCab.Tagger("") __re_hiragana__ = re.compile(u"[あ-ん]+") def get_nouns(sentence): ''' 日本語文(sentence)(UTF-8)から名詞抽出してリストを返す。 ''' node = __mecab__.parseToNode(sentence) res = [] while node: pos = node.feature.split(",", 1)[0] if pos == MEISHI: res.append(node.surface) node = node.next return res def is_japanese(sentence): ''' sentence(Unicode文字列)が日本語かどうか(実際には平仮名を含んでいるか)を返す。 ''' return __re_hiragana__.search(sentence)