python-2.7 - 如何找到单个文档的 tfidf 矩阵中哪个单词具有最大 tfidf?

标签 python-2.7 pandas tf-idf

我目前正在使用以下代码。我已经存储了所有文档的 tfidf 矩阵,现在我需要特定文档的前 n 个单词? 我很困惑如何获得它?

这是我到目前为止使用的代码。我现在需要从每个文档中找到具有最高 tfidf 的单词

import glob
import pandas as pd
import math
filenames=[]
corpus = []
df=pd.DataFrame(columns=['article','similar','score'])
for file in glob.glob("*.txt"):
    with open(file, "r") as paper:
    corpus.append((file, paper.read()))
    filenames.append(file)
from sklearn.feature_extraction.text import TfidfVectorizer

tf = TfidfVectorizer(analyzer='word', ngram_range=(1,1), min_df = 0, stop_words = 'english')
tfidf_matrix =  tf.fit_transform([content for file, content in corpus])

最佳答案

您可以使用np.argmax获取索引,然后使用它在TfidfVectorizer._vocabulary中查找相应的单词,如下所示:

vocab_lookup = {v:k for k,v in tf.vocabulary_.items()}
[vocab_lookup[np.argmax(v)] for v in tfidf_matrix]

关于python-2.7 - 如何找到单个文档的 tfidf 矩阵中哪个单词具有最大 tfidf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44450510/

相关文章:

python-3.x - pandas 计算匹配条件的文本的方法是什么?

python - 检查列中的值是否唯一,如果它们是唯一的,则添加到行尾如果不唯一,则添加不唯一到行尾

使用 TFIDF 的 Python 文本分类

python-2.7 - Python 文本编辑器(非常基础)

python - 如何将多个列表附加到 python 字典中的一个键?

Python:更详细地按日期时间对文件进行排序

python - 操作 TSV 文件

python - 加入具有多个日期的数据框(Vlookup)

python - TfIdf 矩阵返回 BernoulliNB 的特征数量错误

python - Numpy 矩阵维数-tfidf 向量