使用python写一段代码,实现词云图功能
时间: 2023-07-15 08:15:42 浏览: 102
好的,使用Python实现词云图功能可以使用第三方库wordcloud和jieba。
安装依赖库:
```
pip install wordcloud
pip install jieba
```
示例代码:
```python
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 读取文本内容
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 使用jieba分词
words = jieba.cut(content)
# 过滤掉单个字和停用词
stopwords = ['的', '了', '是', '我', '你', '他', '她', '我们', '你们', '他们', '这', '那', '就是', '但是', '和', '也', '吧', '啊']
filtered_words = [word for word in words if len(word) > 1 and word not in stopwords]
# 拼接为字符串
text = ' '.join(filtered_words)
# 生成词云图
wc = WordCloud(width=800, height=400, background_color='white', font_path='msyh.ttc').generate(text)
# 显示词云图
plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.show()
# 保存词云图
wc.to_file('wordcloud.png')
```
说明:
- 示例代码中,读取的文本文件为`example.txt`,可以替换为自己的文本文件;
- `jieba.cut()`函数用于对文本进行分词,返回的是一个可迭代的生成器对象;
- `stopwords`为停用词列表,可以根据需要自行修改;
- `WordCloud()`函数用于生成词云图,其中`width`和`height`分别指定词云图的宽和高,`background_color`指定背景颜色,`font_path`指定字体文件路径;
- `imshow()`函数用于显示词云图;
- `to_file()`函数用于保存词云图,保存路径为`wordcloud.png`,可以根据需要修改。
阅读全文
相关推荐

















