【python】python玩转wordcloud词云

1.引入必要的库:

jieba:用于中文分词。 wordcloud:用于生成词云图。 matplotlib:用于显示词云图。 numpy和PIL:用于处理图像,如设置词云图形状。

2.读取文本:

使用open函数读取文本文件,例如: with open("yourfile.txt", "r", encoding="utf-8") as f: text = f.read()

3.分词处理:

利用jieba进行中文分词,并设置停用词过滤不需要的词汇。

4.设置词云图形状:

可以通过PIL库读取一个PNG图片作为词云的形状。

5.字体设置:

设置词云图使用的字体路径和大小,确保中文显示无误。

6.生成词云图:

使用wordcloud库的WordCloud类生成词云图,并通过matplotlib展示。

示例代码

import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

# 读取文本内容
text = open("yourfile.txt", encoding="utf-8").read()

# 中文分词
words = jieba.cut(text)
words = [word for word in words if len(word) >= 2] # 过滤单个字符

# 设置停用词
stopwords = set(["的", "和", "是"]) # 示例停用词

# 设置词云图形状
mask_image = np.array(Image.open("yourmask.png"))

# 设置字体路径
font_path = "C:\\Windows\\Fonts\\STLITI.TTF"

# 生成词云
wordcloud = WordCloud(
font_path=font_path,
mask=mask_image,
background_color='white',
stopwords=stopwords
).generate(' '.join(words))

# 显示词云图
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()

# 保存词云图
wordcloud.to_file("wordcloud.png")

注意事项

  • 确保安装了所有必要的库,否则代码将无法运行。
  • 字体路径需要根据实际情况进行设置,以确保中文能够正确显示。
  • PNG掩膜图片应该是透明背景的,以便词云能够呈现出预期的形状。

参考链接

TBD

posted @ 2025-01-02 16:40  anliux  阅读(156)  评论(0)    收藏  举报