![]() |
ノート/テキストマイニング/oregano3https://pepper.is.sci.toho-u.ac.jp:443/pepper/index.php?%A5%CE%A1%BC%A5%C8%2F%A5%C6%A5%AD%A5%B9%A5%C8%A5%DE%A5%A4%A5%CB%A5%F3%A5%B0%2Foregano3 |
![]() |
ノート/テキストマイニング
訪問者数 1863 最終更新 2009-02-28 (土) 19:58:25
>>ノート/テキストマイニング/oregano
>>ノート/テキストマイニング/oregano2
2009/02/28
出力をタプル形式にしたので、それなりに使えそうだ。
テキストのDBをアクセスし、出力をchasenで形態素解析し、名詞だけを拾う。
#!/usr/bin/env python # encoding: utf-8 # -*- coding: utf-8 -*- ## ## To run with Kanji properly, the Python default encoding should be set to utf-8. ## This is done by including the file /usr/lib/python2.5/site-packages/sitecustomize.py ## with such lines as ## #!/usr/bin/env python ## import sys ## sys.setdefaultencoding('utf-8') ## To check this is properly set, start python and issue ## import sys ## sys.getdefaultencoding() ## which should reply with utf-8. ## See http://python.matrix.jp/tips/string/encoding.html ## import sys import codecs import MySQLdb import pycha ## これを入れる ### A magic for printing UTF-8 characters sys.stdout = codecs.getwriter('utf_8')(sys.stdout) ## HERE STARTS THE MAIN PROGRAM ## Open DB connection connect = MySQLdb.connect(db="pytest", host="localhost", port=3306, user="******", passwd="******",charset="utf8") cur = connect.cursor() fieldname = 'article' str = "select " + fieldname + " from mytest2" cur.execute(str) ## データベースアクセス(SQL文)実行 rows = cur.fetchall() ## 結果を取出し for row in rows: ## print row[0] t = pycha.pycha(row[0]) ## 入力row[0]を与えてchasenを呼出し for x in t: if (len(x) >= 4): ## 第4フィールドまで無いレコードがあるので確認 hinshi = x[3][:6] ## 第4欄(x[3])=品詞欄、先頭6バイト(UTF8で2文字)抽出 if (hinshi == u'名詞'): ## 品詞欄の先頭2文字が「名詞」であれば print x[0] ## 第1欄(x[0])=元の文字列を印字 print '------' ## レコードごとの区切り ## Close DB connection cur.close() connect.close()
このプログラムを実行した結果(文字コードはUTF-8) > meishi.txt