Python テキストマイニング 名詞を抽出する

テキストマイニングの基本である名詞の抽出と出現回数の集計を行います。日本語形態素解析にはYahoo! の形態素解析サービスを利用して行います。Yahoo! API ライブラリはYusuke Inuzukaさん開発のPythonモジュール yahooapiを使用します。


#!/usr/bin/env python
# vim: set fileencoding=utf-8:
#
# 名詞の出現頻度を数える
__usage__="""
count.py [raw text file] > [output file]
"""

import sys
import os
import operator
from threading import Thread

import yahooapi.jlp as jlp

YAHOO_APPID="ここに自分のアプリケーションIDを書く"

class YAPI(Thread):
def __init__(self, sentence, words):
Thread.__init__(self)
self.client = jlp.MAServiceAPI(YAHOO_APPID)
self.sentence = sentence.decode("utf_8")
self.words = words
#end def __init__

def run(self):
_res = self.client.parse(sentence=self.sentence, results=jlp.UNIQ, filter=jlp.NOUN)
if isinstance(_res.uniq_result.word_list, str):
return
n = len(_res.uniq_result.word_list.word)
if 0 == n:
return
for x in xrange(0, n-1):
try:
_s = _res.uniq_result.word_list.word[x].surface
_c = _res.uniq_result.word_list.word[x].count
except:
continue
if isinstance(_s, int):
continue
if not self.words.has_key(_s):
self.words[_s] = 0
self.words[_s] += _c
return
#end class YAPI

def request(record, words):
reqlist = []
for row in record:
if 1 > len(row.strip()):
continue
current = YAPI(row.strip(), words)
reqlist.append(current)
current.start()
for req in reqlist:
req.join()

if __name__ == '__main__':
try:
fd = file(sys.argv[1], "r")
record = fd.readlines()
fd.close()
except:
print __usage__
sys.exit(0)
words = {}
limit_row = 40
offset = 0
rec_num = len(record)
loop_counter = rec_num / limit_row
if 0 < rec_num % limit_row:
loop_counter += 1
if 0 == loop_counter:
limit_row = rec_num
while 0 < loop_counter:
last = offset + limit_row
request(record[offset:last], words)
loop_counter -= 1
offset += limit_row
# output
items = words.items()
items.sort(key=operator.itemgetter(1), reverse=True)
for word,count in items:
try:
print "%s\t%d" % (word.encode("utf_8"), count)
except:
print "%s\t%d" % (word, count)
sys.exit(0)

入力ファイルのサイズによってはYahoo! APIのリクエスト制限にひっかかるのか、異常終了します。その辺りの例外処理は無いので適当に対処してください。

マルチスレッドで形態素解析を行ないますがスレッド プログラミングがあまりわかっていないので変なプログラムかもしれません。

出力フォーマットは一行に名詞と出現回数をタブ区切りにしています。

comment

管理者にだけメッセージを送る

プロフィール

Author:speirs
Python で何かしてます。IRCNet の #python-ja チャンネルに出没。

最近の記事
最近のコメント
全記事表示リンク

全ての記事を表示する

ライセンス
ブログの記事は、クリエイティブ・コモンズ・ライセンスの下でライセンスされています。
リンク
ブロとも申請フォーム

この人とブロともになる