【问题标题】:Python: Using a list with TF-IDFPython:使用带有 TF-IDF 的列表
【发布时间】:2019-03-25 10:09:04
【问题描述】:

我有以下代码,当前将“令牌”中的所有单词与“df”中的每个文档进行比较。有什么方法可以将预定义的单词列表与文档而不是“令牌”进行比较。

from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer(norm=None)  

list_contents =[]
for index, row in df.iterrows():
    list_contents.append(' '.join(row.Tokens))

# list_contents = df.Content.values

tfidf_matrix = tfidf_vectorizer.fit_transform(list_contents)
df_tfidf = pd.DataFrame(tfidf_matrix.toarray(),columns= [tfidf_vectorizer.get_feature_names()])
df_tfidf.head(10)

感谢任何帮助。谢谢!

【问题讨论】:

  • 嗨@stackyflowy123,欢迎来到!感谢您将一些代码放在这里。您能否举个例子说明您正在尝试做什么以及它是如何不起作用的?

标签: python pandas text tf-idf tfidfvectorizer


【解决方案1】:

不确定我是否理解正确,但如果你想让 Vectorizer 考虑一个固定的单词列表,你可以使用 vocabulary 参数。

my_words = ["foo","bar","baz"]

# set the vocabulary parameter with your list of words
tfidf_vectorizer = TfidfVectorizer(
    norm=None,
    vocabulary=my_words)  

list_contents =[]
for index, row in df.iterrows():
    list_contents.append(' '.join(row.Tokens))

# this matrix will have only 3 columns because we have forced
# the vectorizer to use just the words foo bar and baz
# so it'll ignore all other words in the documents.
tfidf_matrix = tfidf_vectorizer.fit_transform(list_contents) 

【讨论】:

    猜你喜欢
    • 2020-08-25
    • 2016-10-13
    • 2016-03-16
    • 2018-08-22
    • 1970-01-01
    • 2017-07-01
    • 2021-09-28
    • 1970-01-01
    • 2015-04-17
    相关资源
    最近更新 更多