词云要求背景为白底,所以先找一张白底的图片,或者你找纯色的背景,通过PS将背景改成白色
如图
同时从网上下载你希望统计词云的txt,如我就下载了知否知否应是绿肥红瘦的txt
然后将图片和txt放到与源代码同一个文件夹,执行下面代码即可
import wordcloud
import jieba
from imageio import imread
mask = imread("七夕.jpg")
f = open("知否.txt","r", encoding = "utf-8")
t = f.read()
f.close()
ls = jieba.lcut(t)
txt = " ".join(ls)
w = wordcloud.WordCloud(width = 1000,font_path = "msyh.ttc"\
,height = 700,background_color = "white"\
,max_words=50,mask = mask)
w.generate(txt)
w.to_file("七夕词云.png")
结果如下