安装必要的库
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()
常用参数