Python实现词云
时间: 2023-11-29 18:46:27 浏览: 61
以下是Python实现词云的步骤和代码示例:
1.安装 wordcloud 库和 matplotlib 库
```shell
pip install wordcloud matplotlib
```
2.导入所需库
```python
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
```
3.准备文本和遮罩图片
```python
text = 'Python编程非常有趣,是一门易学难精的编程语言。'
mask = np.array(Image.open('heart.jpg'))
```
4.生成词云
```python
wc = WordCloud(background_color='white', mask=mask, contour_width=3, contour_color='steelblue')
wc.generate(text)
```
5.显示词云
```python
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.show()
```
6.保存词云
```python
wc.to_file('wordcloud.png')
```
完整代码如下:
```python
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
text = 'Python编程非常有趣,是一门易学难精的编程语言。'
mask = np.array(Image.open('heart.jpg'))
wc = WordCloud(background_color='white', mask=mask, contour_width=3, contour_color='steelblue')
wc.generate(text)
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.show()
wc.to_file('wordcloud.png')
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)