一个五角星形状制作一个中文词云Python
时间: 2024-02-05 21:10:40 浏览: 122
要制作中文词云,我们需要用到 Python 的词云库和中文分词库。这里我使用 jieba 和 wordcloud 库。
首先需要安装这两个库,使用以下命令安装:
```
pip install jieba
pip install wordcloud
```
接下来,我们可以先定义一个五角星形状的 mask,用于词云的形状。
```python
import numpy as np
from PIL import Image
from wordcloud import WordCloud, STOPWORDS
import jieba
# 读取 mask 图片
mask = np.array(Image.open("star.png"))
```
然后,我们需要读取文本文件,并进行中文分词和去除停用词,得到词频统计结果。
```python
# 读取文本文件
with open("text.txt", "r", encoding="utf-8") as f:
text = f.read()
# 中文分词
seg_list = jieba.cut(text)
# 去除停用词
stopwords = set(STOPWORDS)
stopwords.add("的")
stopwords.add("在")
stopwords.add("了")
words = [word for word in seg_list if word not in stopwords]
# 计算词频
word_freq = {}
for word in words:
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
# 排序
sorted_word_freq = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)
```
接下来就可以用词频结果生成词云了。
```python
# 创建 WordCloud 对象
wc = WordCloud(background_color="white", mask=mask, max_words=2000, contour_width=3, contour_color="steelblue")
# 生成词云
wc.generate_from_frequencies(dict(sorted_word_freq))
# 保存词云图片
wc.to_file("wordcloud.png")
```
最后,我们可以将生成的词云图片显示出来。
```python
# 显示词云图片
import matplotlib.pyplot as plt
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()
```
完整代码如下:
```python
import numpy as np
from PIL import Image
from wordcloud import WordCloud, STOPWORDS
import jieba
import matplotlib.pyplot as plt
# 读取 mask 图片
mask = np.array(Image.open("star.png"))
# 读取文本文件
with open("text.txt", "r", encoding="utf-8") as f:
text = f.read()
# 中文分词
seg_list = jieba.cut(text)
# 去除停用词
stopwords = set(STOPWORDS)
stopwords.add("的")
stopwords.add("在")
stopwords.add("了")
words = [word for word in seg_list if word not in stopwords]
# 计算词频
word_freq = {}
for word in words:
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
# 排序
sorted_word_freq = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)
# 创建 WordCloud 对象
wc = WordCloud(background_color="white", mask=mask, max_words=2000, contour_width=3, contour_color="steelblue")
# 生成词云
wc.generate_from_frequencies(dict(sorted_word_freq))
# 保存词云图片
wc.to_file("wordcloud.png")
# 显示词云图片
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()
```
注意,这里的 mask 图片需要是一个 PNG 格式的图片,其中五角星形状为白色,背景为黑色。可以在网上搜索五角星的 PNG 图片,或者使用其他自定义形状的图片。
阅读全文
相关推荐












