测试例子:
#coding:utf-8
from wordcloud import WordCloud, ImageColorGenerator
import matplotlib.pyplot as plt
import numpy
from PIL import Image
import io
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
def doWordCloud():
txt = io.open("test.txt",'r',encoding='GBK').read()
image = numpy.array(Image.open('./test.jpg'))
wc = WordCloud(
background_color="black",
font_path="C:/Windows/Fonts/STKAITI.TTF",
max_font_size=60,
max_words=3000,
mask = image,
).generate(txt)
plt.figure(figsize=(10,10))
#重定向颜色
image_color = ImageColorGenerator(image)
plt.imshow(wc.recolor(color_func=image_color))
plt.axis('off')
plt.show()
#保存图片
wc.to_file("./result.jpg")
def start():
doWordCloud()
def main():
start()
if __name__=="__main__":
main()
测试数据:https://new.qq.com/omn/20210302/20210302A0DZHY00.html
测试结果: