WordCloud

安装必要的库

pip install wordcloud matplotlib
pip install jieba  # 如果需要中文支持,还需安装中文分词库

基本用法

from wordcloud import WordCloud
import matplotlib.pyplot as plt
import jieba

# 读取文本文件
with open("text.txt", "r", encoding="utf-8") as file:
    text = file.read()

# 中文分词处理
text = " ".join(jieba.cut(text))

# 创建词云对象
wordcloud = WordCloud(
    font_path="C:/WINDOWS/Fonts/msyh.ttc",
    width=1200,
    height=800,
    background_color="white",
    colormap="coolwarm",
).generate(text)

# 绘制词云
plt.figure(figsize=(12, 8))
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.savefig("wc.png")
plt.show()

常用参数

  • width 和 height:设置词云图的宽度和高度(像素)。
  • background_color:背景颜色(如 'white'、'black' 或任意颜色代码)。
  • min_font_size 和 max_font_size:字体大小范围。
  • max_words:显示的最大词数。
  • stopwords:忽略的停用词集合(如 {'is', 'and', 'the'})。
  • font_path:指定字体路径(对中文支持很重要)。
  • colormap:颜色映射(如 'viridis'、'plasma')。
  • mask:自定义词云形状
    mask = np.array(Image.open('mask.png'))  # 假设有模板是 mask.png

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注