【发布时间】:2018-06-12 03:37:14
【问题描述】:
我在我的文档语料库中使用来自here 的 TF-IDF 代码,这是 3 个 PDF 文档,每个大约 270 页长。
# Calculating the Term Frequency, Inverse Document Frequency score
import os
import math
from textblob import TextBlob as tb
def tf(word, blob):
return tb(blob).words.count(word) / len(tb(blob).words)
def n_containing(word, bloblist):
return sum(1 for blob in bloblist if word in tb(blob).words)
def idf(word, bloblist):
return math.log(len(bloblist) / (1 + n_containing(word, bloblist)))
def tfidf(word, blob, bloblist):
return tf(word, blob) * idf(word, bloblist)
# Stemming the articles
from nltk.stem import PorterStemmer
port = PorterStemmer()
bloblist = []
doclist = [pdf1, pdf2, pdf3] # Defined earlier, not showing here as it is not relevant to the question
for doc in doclist:
bloblist.append(port.stem(str(doc)))
# TF-IDF calculation on the stemmed articles
for index, blob in enumerate(bloblist):
print("Top words in document {}".format(index + 1))
scores = {word: tfidf(word, blob, bloblist) for word in tb(blob).words}
sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)
i=1
for word, score in sorted_words[:5]:
print("\tWord "+str(i)+": {}, TF-IDF: {}".format(word, round(score, 5)))
i+=1
问题是,它只是继续运行,除了Top words in document 1 之外没有显示任何内容。为什么计算scores 需要这么长时间?我已经让它运行了一个小时,并且代码还没有终止。早些时候,我尝试了 50 个长度更短的 txt 文件的代码(例如,平均 2-3 段),它能够立即显示 TF-IDF 分数。 3 个 270 页的文档有什么问题?
【问题讨论】:
标签: python dictionary nlp tf-idf