python生成词云图
时间: 2023-10-13 07:19:46 浏览: 73
生成词云图的步骤如下:
1.导入需要的库
```python
import jieba
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
```
2.读取文本文件并进行分词处理
```python
text = open('text.txt', 'r', encoding='utf-8').read()
cut_text = jieba.cut(text)
result = ' '.join(cut_text)
```
3.设置停用词和自定义词典
```python
stopwords = set(STOPWORDS)
stopwords.add('的')
stopwords.add('是')
stopwords.add('在')
stopwords.add('等')
stopwords.add('有')
stopwords.add('就')
stopwords.add('了')
stopwords.add('和')
stopwords.add('我')
stopwords.add('你')
stopwords.add('他')
userdict = 'userdict.txt'
jieba.load_userdict(userdict)
```
4.生成词云图
```python
mask = np.array(Image.open('mask.png'))
wc = WordCloud(font_path='simhei.ttf', background_color='white', max_words=2000, mask=mask, stopwords=stopwords)
wc.generate(result)
image_colors = ImageColorGenerator(mask)
plt.figure(figsize=[10, 10])
plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")
plt.axis("off")
plt.show()
```
其中,`text.txt`是要生成词云图的文本文件,`userdict.txt`是自定义词典文件,`mask.png`是词云图的形状,可以根据需要自行选择。在生成词云图时,可以设置字体、背景颜色、最大词数等参数,具体可以参考WordCloud库的官方文档。
阅读全文
相关推荐













