如何调整wordcloud代码基于Pandas按Sentiment条件生成负面文本词云
实现仅针对Negative情感文本生成词云的调整方案
关键修改逻辑
- 不需要改动原有词云的配色、背景、画布大小等设置,只需要在拼接词云用的长文本之前,用Pandas布尔索引过滤出
Sentiment列值为Negative的行,再从过滤后的子集里提取Text字段做拼接。 - 布尔索引筛选无需循环遍历全表判断每行的情感值,数据量大时运行效率远高于逐行遍历的写法。
- 如果
Sentiment列的标签存在大小写不统一的问题(比如标注为negative、NEGATIVE),可以先把列值统一转成大写/小写再做匹配,避免漏选目标文本。
调整后的完整可运行代码
from wordcloud import WordCloud from matplotlib import colors import matplotlib.pyplot as plt from nltk.corpus import stopwords color_list=['#4d4d4d','#ffcc00','#000000',] colormap=colors.ListedColormap(color_list) # 过滤出情感标签为Negative的行,提取文本拼接为词云输入 negative_rows = df[df['Sentiment'] == "Negative"] words = ' '.join(negative_rows['Text'].tolist()) wordCloud = WordCloud( background_color='white', colormap=colormap, mode="RGB", width=2000, height=1000 ).generate(words) plt.figure(figsize=(20,10)) plt.imshow(wordCloud) plt.axis("off") # 可选配置:隐藏冗余的坐标轴刻度,让词云展示更整洁 plt.show()
内容的提问来源于stack exchange,提问作者Stefano
相关产品推荐
相关产品推荐

