已知excel中已经对不同的情感类别评论做出了分析,分别用0、-1和1表示,现在要通过Python对不同情感类别评论绘制出词云图
时间: 2024-03-09 14:46:53 浏览: 16
好的,您可以使用Python中的wordcloud库和matplotlib库来实现这个功能。下面是一个简单的实现步骤:
1. 读取Excel文件,将不同情感类别的评论分别保存到不同的列表中。
2. 将每个列表中的评论合并成一个字符串。
3. 使用正则表达式清除字符串中的标点符号和数字等无用字符。
4. 使用wordcloud库生成词云图。
5. 使用matplotlib库展示词云图。
下面是一个简单的示例代码:
```python
import pandas as pd
import re
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 读取Excel文件
df = pd.read_excel('comments.xlsx')
# 将不同情感类别的评论分别保存到不同的列表中
positive_comments = df[df['sentiment'] == 1]['comment'].tolist()
negative_comments = df[df['sentiment'] == -1]['comment'].tolist()
neutral_comments = df[df['sentiment'] == 0]['comment'].tolist()
# 将每个列表中的评论合并成一个字符串
positive_text = " ".join(positive_comments)
negative_text = " ".join(negative_comments)
neutral_text = " ".join(neutral_comments)
# 使用正则表达式清除字符串中的标点符号和数字等无用字符
positive_text = re.sub('[^a-zA-Z]', ' ', positive_text)
negative_text = re.sub('[^a-zA-Z]', ' ', negative_text)
neutral_text = re.sub('[^a-zA-Z]', ' ', neutral_text)
# 使用wordcloud库生成词云图
positive_wordcloud = WordCloud(width=800, height=800, background_color='white').generate(positive_text)
negative_wordcloud = WordCloud(width=800, height=800, background_color='white').generate(negative_text)
neutral_wordcloud = WordCloud(width=800, height=800, background_color='white').generate(neutral_text)
# 使用matplotlib库展示词云图
fig, axes = plt.subplots(1, 3, figsize=(15,15))
axes[0].imshow(positive_wordcloud)
axes[0].set_title('Positive Comments')
axes[0].axis('off')
axes[1].imshow(negative_wordcloud)
axes[1].set_title('Negative Comments')
axes[1].axis('off')
axes[2].imshow(neutral_wordcloud)
axes[2].set_title('Neutral Comments')
axes[2].axis('off')
plt.show()
```
在这个示例代码中,我们首先读取了Excel文件,并将不同情感类别的评论分别保存到了不同的列表中。然后,我们将每个列表中的评论合并成了一个字符串,并使用正则表达式清除了无用字符。接下来,我们使用wordcloud库生成了词云图,并使用matplotlib库展示了词云图。最终的结果是在一个包含三个子图的画布上展示了三个不同情感类别的评论词云图。