Python:使用带有TF-IDF的列表

Python:使用带有TF-IDF的列表,python,pandas,text,tf-idf,tfidfvectorizer,Python,Pandas,Text,Tf Idf,Tfidfvectorizer,我有下面一段代码,它当前将“Tokens”中的所有单词与“df”中的每个文档进行比较。是否有任何方法可以将预定义的单词列表与文档而不是“标记”进行比较 from sklearn.feature_extraction.text import TfidfVectorizer tfidf_vectorizer = TfidfVectorizer(norm=None) list_contents =[] for index, row in df.iterrows(): list_conte

我有下面一段代码,它当前将“Tokens”中的所有单词与“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)

感谢您的帮助。谢谢大家!

< P>不确定是否正确理解,但如果要使向量化器考虑一个固定的单词列表,可以使用词汇参数。

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) 

你好@stackyflowy123,欢迎来到SO!谢谢你把一些代码放在这里。你能给我们举个例子,说明你想做什么,以及它是如何不起作用的吗?