【问题标题】:wordcloud for a csv file in pythonpython中csv文件的wordcloud
【发布时间】:2017-06-30 18:52:54
【问题描述】:

我有一个包含 2 列的 csv 文件(数据框) 第 1 列包含一个句子我爱香蕉

第 2 列包含我拥有的一个类 5 classes

我需要每个班级都有一个 wordcloud 其实每一个所有的句子都对应每一个类有可能做到吗? 它尝试此代码,但 id 不起作用

import matplotlib.pyplot as plt
cloud = WordCloud(background_color="white", max_words=20, stopwords=stopwords)
tuples = tuple([tuple(x) for x in df.Phrase.value_counts().reset_index().values])
a = cloud.generate_from_frequencies(tuples)

plt.imshow(a)
plt.axis("off")
plt.title("a")
plt.show()

数据集示例

text                           classe
i love banana                 positive 
i hate banana                 negetive
maybe i love maybe no         neutral
bit yes bit no                not_sure
wooooooooooow                 like_it

【问题讨论】:

  • @MaxU 是的,我修改了描述
  • @MaxU 是的,我修改了描述
  • 是的,我注意到了。我目前正在学习wordcloud 的工作原理...... ;)
  • 如果我理解正确,您想要 5 张图片(云) - 每班一张,我没听错吗?
  • @MaxU 正是我所需要的

标签: python csv pandas classification word-cloud


【解决方案1】:

这是一个类的示例:positive

假设我们有以下DF:

In [79]: df
Out[79]:
                    text    classe
0          i love banana  positive
1             love apple  positive
2       love, love, love  positive
3          i hate banana  negative
4               it sucks  negative
5  maybe i love maybe no   neutral
6         bit yes bit no  not_sure
7          wooooooooooow   like_it

解决方案:

In [80]: %paste
from wordcloud import WordCloud
from nltk.corpus import stopwords

cloud = WordCloud(background_color="white", max_words=20, stopwords=stopwords.words('english'))

positive_cloud = cloud.generate(df.loc[df.classe == 'positive', 'text'].str.cat(sep='\n'))
plt.figure()
plt.imshow(positive_cloud)
plt.axis("off")
plt.show()
## -- End pasted text --

结果:

一些解释:

为单个 class 生成文本:

In [81]: df.loc[df.classe == 'positive', 'text'].str.cat(sep='\n')
Out[81]: 'i love banana\nlove apple\nlove, love, love'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 2016-02-24
    相关资源
    最近更新 更多