如何在Python中从数据帧显示wordcloud

2024-09-28 18:51:36 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,我有一个包含单词和权重(tf*idf)的数据帧,我想在wordcloud中显示按权重排列的单词。在

数据帧在左侧图像上。在

def generate_wordcloud(words_tem):
    word_cloud = WordCloud(width = 512, height = 512, background_color='white', stopwords= None, max_words=20).generate(words_tem)
    plt.figure(figsize=(10,8),facecolor = 'white', edgecolor='blue')
    plt.imshow(word_cloud, interpolation='bilinear')
    plt.axis('off')
    plt.tight_layout(pad=0)
    plt.show()


tfidf = TfidfVectorizer(data, lowercase = False)
tfs = tfidf.fit_transform([data]) 

feature_names = tfidf.get_feature_names()

df = pd.DataFrame(tfs.T.toarray(), index=feature_names, columns= ['weight'])
df = df.sort_values(by = 'weight', ascending = False)
word_lists = df.index.values
unique_str  = ' '.join(word_lists)
print(df[0:20])
generate_wordcloud(unique_str)

enter image description here


Tags: 数据clouddfnamesplt单词generatefeature
1条回答
网友
1楼 · 发布于 2024-09-28 18:51:36

最常用的包是wordcloud。看到了吗 https://github.com/amueller/word_cloud/blob/master/README.md

python -m pip install wordcloud

你可以这样做:

^{pr2}$

类似于上面,而不是文字,你的流程 #从TF-IDF模型开始步骤gensim.模型导入TfidfModel,但你的也可以,因为我们只需创建一个元组(term,weight)。在

tfidf = TfidfModel(vectors)

# Get TF-IDF weights

weights = tfidf[vectors[0]]


# Get terms from the dictionary and pair with weights

weights = [(dictionary[pair[0]], pair[1]) for pair in weights]


# Generate the cloud

wc = WordCloud()
wc.generate_from_frequencies(weights)
...

相关问题 更多 >