注意
window系统安装wordcloud模块时可能会出现需要安装C++等错误,此时使用https://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy网站的whl自己进行安装将不会再报错
import wordcloud as wc # 词云模块
import matplotlib.pylab as plb
import pandas as pda
import jieba # jieba模块 分解词语
from PIL import Image
from numpy import array
path = "C:/Users/Administrator/Desktop/老九门.txt"
data = open(path, "r", encoding="gbk").read() # 读取txt小说文件
cutdata = jieba.cut(data) # 将文本分割成词语
alldata = ""
for i in cutdata: # 词语进行循环拼接
alldata = alldata + " " + str(i)
font = r"C:\WINDOWS\Fonts\simhei.ttf"
# 打开图片
cat = Image.open("C:/Users/Administrator/Desktop/cat.png")
catarray = array(cat) # 将读取的图片转化成数组
# 使用WordCloud方法
oldwc = wc.WordCloud(mask=catarray, collocations=False, # mask展示形状,background_color背景颜色
font_path=font, background_color="white"
).generate(data)
plb.imshow(oldwc)
plb.show()
最终展示结果