#!/usr/bin/env python
import math
from operator import itemgetter
def freq(word, document):
open (r'd:\fenci.txt')
return document.split(None).count(word)
def wordCount(document):
open (r'd:\fenci.txt')
return len(document.split(None))
def numDocsContaining(word,documentList):
count = 0
for document in documentList:
if freq(word,document) > 0:
count += 1
return count
def tf(word, document):
open (r'd:\fenci.txt')
return (freq(word,document) / float(wordCount(document)))
def idf(word, documentList):
open (r'd:\fenci.txt')
return math.log(len(documentList) / numDocsContaining(word,documentList))
def tfidf(word, document, documentList):
open (r'd:\fenci.txt')
return (tf(word,document) * idf(word,documentList))
if __name__ == '__main__':
documentList = []
documentList.append('d:\語料.txt')
documentList.append('D:\分詞.txt')
words = {}
documentNumber=0
for word in documentList[documentNumber].split(None):
words[word] = tfidf(word,documentList[documentNumber],documentList)
for item in sorted(words.items(), key=itemgetter(1), reverse=True):
print( "%f <= %s" % (item[1], item[0]))
為什麼實現不了關鍵詞提取呢?請高手幫忙