python词云 生成简单
时间: 2023-10-14 21:11:06 浏览: 51
生成词云的步骤如下:
1. 安装相关的库:`pip install wordcloud jieba matplotlib`
2. 准备文本文件,读入文本并进行分词处理。这里以中文文本为例:
```
import jieba
# 读入文本文件
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 对文本进行分词
words = jieba.cut(text)
```
3. 统计单词出现的频率,并生成词云:
```
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 统计单词出现的频率
word_freq = {}
for word in words:
if word not in word_freq:
word_freq[word] = 1
else:
word_freq[word] += 1
# 生成词云
wc = WordCloud(background_color='white', width=800, height=600)
wc.generate_from_frequencies(word_freq)
# 显示词云
plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.show()
```
完整代码如下:
```
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)
# 统计单词出现的频率
word_freq = {}
for word in words:
if word not in word_freq:
word_freq[word] = 1
else:
word_freq[word] += 1
# 生成词云
wc = WordCloud(background_color='white', width=800, height=600)
wc.generate_from_frequencies(word_freq)
# 显示词云
plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.show()
```
阅读全文