python词云图怎么做
时间: 2023-10-12 22:16:12 浏览: 39
要制作 Python 词云图,可以使用第三方库 wordcloud 和 matplotlib。下面是一个简单的示例代码:
```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()
# 分词
words = jieba.cut(text)
# 统计词频
freq = {}
for word in words:
if word in freq:
freq[word] += 1
else:
freq[word] = 1
# 生成词云图
wc = WordCloud(font_path='msyh.ttc', width=800, height=600, background_color='white')
wc.generate_from_frequencies(freq)
# 显示词云图
plt.imshow(wc)
plt.axis('off')
plt.show()
```
这段代码的具体步骤如下:
1. 读取文本文件(假设为 text.txt)。
2. 使用 jieba 分词库对文本进行分词。
3. 统计每个词的出现次数,得到一个词频字典 freq。
4. 使用 wordcloud 库生成词云图,设置字体、画布大小和背景色等参数。
5. 使用 matplotlib 库显示词云图。