写一个生成词云图的代码
时间: 2023-04-03 16:01:23 浏览: 93
好的,以下是生成词云图的 Python 代码:
```python
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 读取文本文件
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用 jieba 分词
words = jieba.cut(text)
# 过滤掉停用词
stopwords = set(['的', '了', '是', '我', '你', '他', '她'])
filtered_words = [word for word in words if word not in stopwords]
# 统计词频
word_counts = {}
for word in filtered_words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
# 生成词云图
wc = WordCloud(font_path='msyh.ttc', width=800, height=600, background_color='white')
wc.generate_from_frequencies(word_counts)
# 显示词云图
plt.imshow(wc)
plt.axis('off')
plt.show()
```
请注意,以上代码仅供参考,具体实现可能需要根据实际情况进行调整。
阅读全文