如何利用python生成词云相关代码
时间: 2024-05-14 16:17:17 浏览: 106
生成词云的代码可以使用Python的第三方库`wordcloud`,可以用以下步骤来生成词云:
1. 安装`wordcloud`库,可以使用以下命令进行安装:
```
pip install wordcloud
```
2. 导入`wordcloud`和`matplotlib`库:
```
import wordcloud
import matplotlib.pyplot as plt
```
3. 读取文本文件并进行分词:
```
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
words = jieba.cut(text)
```
4. 将分词结果转化为字符串并生成词云:
```
text = " ".join(words)
wc = wordcloud.WordCloud(width=800, height=600, background_color='white')
wc.generate(text)
```
5. 使用`matplotlib`库展示生成的词云:
```
plt.imshow(wc)
plt.axis('off')
plt.show()
```
完整代码如下:
```
import wordcloud
import matplotlib.pyplot as plt
import jieba
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
words = jieba.cut(text)
text = " ".join(words)
wc = wordcloud.WordCloud(width=800, height=600, background_color='white')
wc.generate(text)
plt.imshow(wc)
plt.axis('off')
plt.show()
```
阅读全文