python制作词云图
时间: 2023-11-24 09:01:35 浏览: 26
制作词云图需要使用Python中的wordcloud库。下面是一个简单的例子:
```python
# 导入必要的库
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 读取文本文件
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用jieba分词
words = jieba.cut(text)
# 将分词结果转换为字符串
text = ' '.join(words)
# 创建WordCloud对象
wc = WordCloud(font_path='simsun.ttc', background_color='white', width=800, height=600)
# 生成词云图
cloud = wc.generate(text)
# 显示词云图
plt.imshow(cloud)
plt.axis('off')
plt.show()
# 保存词云图
cloud.to_file('wordcloud.png')
```
其中,需要将文本文件放在与Python脚本同一目录下,并且使用相应的中文字体文件(如simsun.ttc)。可以根据需要自行调整词云图的大小、背景颜色等参数。
相关问题
python制作词云图代码
以下是使用 Python 制作词云图的示例代码:
```python
# 导入需要用到的库
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 读取文本数据
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 对文本进行分词
cut_text = " ".join(jieba.cut(text))
# 生成词云图
wordcloud = WordCloud(
font_path="simsun.ttc", # 设置字体
background_color="white", # 设置背景颜色
max_words=2000, # 设置最大显示的词数
width=1000, # 设置画布的宽度
height=860, # 设置画布的高度
margin=2 # 设置词与词之间的间距
).generate(cut_text)
# 展示词云图
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
```
解释一下代码:
1. 使用 `jieba` 库对文本进行分词。
2. 使用 `WordCloud` 类生成词云图。
3. 调用 `imshow()` 函数展示词云图。
利用python制作词云图
制作词云图可以使用Python中的`wordcloud`库。以下是一个简单的例子:
```python
# 导入所需库
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 读取文本文件
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 生成词云图
wordcloud = WordCloud(background_color='white', width=800, height=600).generate(text)
# 显示词云图
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
```
其中,`text.txt`为要制作词云图的文本文件名。需要注意的是,如果文本文件中包含中文,需要指定文件编码为`utf-8`。
如果要对词云图进行更多的自定义设置,可以修改`WordCloud`函数中的参数。例如,`background_color`参数可以设置词云图的背景颜色,`width`和`height`参数可以设置词云图的大小等。更多参数可以参考`wordcloud`库的官方文档。