Python tf idf算法
Python Tf idf algorithm
我想在一组文档中找到最相关的词。
我想在 3 个文档和 return 包含每个单词及其频率的 csv 文件上调用 Tf Idf 算法。
以后我只取高数的,我会用。
我发现这个实现可以满足我的需要 https://github.com/mccurdyc/tf-idf/。
我使用 subprocess
库调用该 jar。但该代码存在一个巨大的问题:它在分析单词时犯了很多错误。它混合了一些词,'
和 -
有问题(我认为)。我在 3 本书(哈利波特)的文本上使用它,例如,我在 csv 文件中获取 hermiones, hermionell, riddlehermione, thinghermione
而不是 hermione
之类的词。
我做错了什么吗?你能给我一个 Tf idf 算法的工作实现吗?是否有 python 库可以做到这一点?
这里是使用 scikit-learn 实现 Tf-idf 算法。
在应用它之前,你可以word_tokenize()
and 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)
我想在一组文档中找到最相关的词。
我想在 3 个文档和 return 包含每个单词及其频率的 csv 文件上调用 Tf Idf 算法。
以后我只取高数的,我会用。
我发现这个实现可以满足我的需要 https://github.com/mccurdyc/tf-idf/。
我使用 subprocess
库调用该 jar。但该代码存在一个巨大的问题:它在分析单词时犯了很多错误。它混合了一些词,'
和 -
有问题(我认为)。我在 3 本书(哈利波特)的文本上使用它,例如,我在 csv 文件中获取 hermiones, hermionell, riddlehermione, thinghermione
而不是 hermione
之类的词。
我做错了什么吗?你能给我一个 Tf idf 算法的工作实现吗?是否有 python 库可以做到这一点?
这里是使用 scikit-learn 实现 Tf-idf 算法。
在应用它之前,你可以word_tokenize()
and 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)