Skip to main content
 首页 » 编程设计

Python Tf idf算法

2025年05月04日21lhb25

我想在一组文档中找到最相关的词。

我想对 3 个文档调用 Tf Idf 算法并返回一个包含每个单词及其频率的 csv 文件。

在那之后,我将只取那些数字高的,然后我会使用它们。

我发现这个实现可以满足我的需要 https://github.com/mccurdyc/tf-idf/ .

我使用 subprocess 库调用该 jar。但该代码存在一个巨大的问题:它在分析单词时犯了很多错误。它混合了一些词,它在 ' 和 - 方面有问题(我认为)。我在 3 本书(哈利波特)的文本中使用它,例如,我正在获取诸如 hermiones, hermionell, riddlehermione, thinghermione 而不仅仅是 hermione 的词csv 文件。

我做错了什么吗?你能给我一个 Tf idf 算法的工作实现吗?是否有执行此操作的 Python 库?

请您参考如下方法:

这是使用 scikit-learn 实现的 Tf-idf 算法. 在申请之前,您可以word_tokenize()和 stem你的话。

import pandas as pd 
from sklearn.feature_extraction.text import TfidfVectorizer 
from nltk import word_tokenize 
from nltk.stem.porter import PorterStemmer 
 
def tokenize(text): 
    tokens = word_tokenize(text) 
    stems = [] 
    for item in tokens: stems.append(PorterStemmer().stem(item)) 
    return stems 
 
# your corpus 
text = ["This is your first text book", "This is the third text for analysis", "This is another text"] 
# word tokenize and stem 
text = [" ".join(tokenize(txt.lower())) for txt in text] 
vectorizer = TfidfVectorizer() 
matrix = vectorizer.fit_transform(text).todense() 
# transform the matrix to a pandas df 
matrix = pd.DataFrame(matrix, columns=vectorizer.get_feature_names()) 
# sum over each document (axis=0) 
top_words = matrix.sum(axis=0).sort_values(ascending=False)