我有一个名为corpus
的列表,想要使用内置的sklearn
函数对其进行TF-IDF。该列表有5个项目,这些项目来自文本文件。
为了举例子,我已经生成了一个名为corpus的玩具列表。
corpus = ['Hi what are you accepting here do you accept me',
'What are you thinking about getting today',
'Give me your password to get accepted into this school',
'The man went to the tree to get his sword back',
'go away to a far away place in a foreign land']
vectorizer = TfidfVectorizer(stop_words='english')
vecs = vectorizer.fit_transform(corpus)
feature_names = vectorizer.get_feature_names()
dense = vecs.todense()
lst1 = dense.tolist()
df = pd.DataFrame(lst1, columns=feature_names)
df
使用上述代码,我能够得到一个包含5行数据(每个列表项都有一行)和n列tf-idf值的数据框。该值是针对语料库中每个单词的。
下一步,我希望构建一个词云,其中包含整个语料库中具有最高权重的tf-idf值最大的单词。
我尝试了以下方法:
x = vectorizer.vocabulary_
Cloud = WordCloud(background_color="white", max_words=50).generate_from_frequencies(x)
这显然行不通。该词典是一个带有索引的单词列表,而不是单词评分。
因此,我需要一个将TF-IDF得分分配给语料库中每个单词的词典。然后,所生成的词云将以得分最高的单词作为最大的尺寸。
generate_from_frequencies
而不是generate
。 - Katya