python利用jieba和wordcloud生成词云图怎么做
时间: 2024-05-08 22:15:58 浏览: 102
Python利用jieba和wordcloud生成词云图的方法如下:
1. 安装jieba和wordcloud库:
```
pip install jieba
pip install wordcloud
```
2. 导入需要的库:
```python
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
```
3. 读取文本文件并进行分词:
```python
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
words = jieba.cut(text)
```
4. 将分好的词转换为字符串并使用WordCloud生成词云图:
```python
wordcloud = WordCloud(font_path='msyh.ttc', width=800, height=600, background_color='white').generate(' '.join(words))
plt.imshow(wordcloud)
plt.axis('off')
plt.show()
```
其中,`font_path`指定字体文件路径,`width`和`height`为词云图的宽度和高度,`background_color`为背景颜色,默认为黑色。最后一步使用`plt.imshow()`显示词云图,并使用`plt.axis('off')`去掉坐标轴,最后使用`plt.show()`显示词云图。
完整代码示例:
```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)
# 生成词云图
wordcloud = WordCloud(font_path='msyh.ttc', width=800, height=600, background_color='white').generate(' '.join(words))
# 显示词云图
plt.imshow(wordcloud)
plt.axis('off')
plt.show()
```
阅读全文