専門用語抽出するための TF-IDF をPython で書いた
DBCLSでやってる自然言語処理の話。
TF * IDFは ある単語が、その単語を含む文書において、全体の文書と比較しながら「どれぐらい非凡か」ということを示す。
スコア = (ドキュメントに含まれる特定の単語の数/ドキュメントに含まれる全単語数) / log(全ドキュメント数 / 特定の単語を含むドキュメント数)
専門文書に含まれる専門用語を、青空文庫のログで比較して専門用語のスコアを高くとれるか、ということに使う。
まだ単語の抽出が済んでないので、スコアはあとで。
#/usr/bin/python #-*- encoding:utf-8 -*- import os import MeCab from sys import argv from math import log from glob import glob mecab = MeCab.Tagger("-Ochasen") class TFIDF(object): def __init__(self, documents_path): self.documents_path = documents_path def count_docs(self): cnt = 0 for i in self.documents_path: cnt += len(glob(""+i+"*")) return cnt def count_pop_docs(self,word): cnt = 0 for path in self.documents_path: for i in glob(path +"*"): text = open(i).read() if self.count_nown(text,word,verbose=False)[0] > 0: cnt += 1 return cnt def count_nown(self,text,word,verbose=True): nown_cnt = 0 word_cnt = 0 node= mecab.parseToNode(text) while node.next: node = node.next if node.feature.split(",")[0] == "名詞": nown_cnt +=1 if node.surface == word: word_cnt += 1 if verbose:print ""+""+"名詞:"+str(nown_cnt),word+":"+str(word_cnt) return word_cnt ,nown_cnt def get_tf(self,doc,word): text = open(doc).read() word_cnt , nown_cnt = self.count_nown(text,word) return 1.0 * word_cnt / nown_cnt def get_idf(self,word): word_pop_count = self.count_pop_docs(word) number = self.count_docs() print "全"+str(number)+"ドキュメントの中、「"+word+"」は"+str(word_pop_count)+"個数存在" return log(1.0 * number / word_pop_count) def count(self,doc , word): tf = self.get_tf(doc , word) idf = self.get_idf(word) return 1.0*tf * idf documents_path = [ # 青空文庫を置いたディレクトリ "/Users/mizchi/aozora/" ] doc = "/Users/mizchi/dbcls/pne/2006/2375_51_2006.txt" # 解析対象のドキュメント word = "DNA" #テストしたい単語 score = tfidf.count(doc,word) print ""+ doc +"の"+word+"のTF-IDFスコアは"+score+"です"