准备评论文本
1、先像这样,从网上摘一些沙雕网友的评论
2、再看看wordcloud库的语法
a、 w=wordcloud.WordCloud(height,width,font_path,max_words,max_font_size,min_font_size,background_color,mask)
生成一个wordcloud对象
b、w.generate(content)向w对象添加内容
c、w.to_file\html\image(‘filename’)将内容输出到文件
开始写脚本
import wordcloud as wdc
comment = open('wyy.txt','r',encoding='utf-8')
w = wdc.WordCloud(font_path='simhei.ttf',height=1080,width=1920,background_color='white')
w.generate(comment.read())
comment.close()
w.to_file('网抑云.jpg')
就会在当前目录下生成一张包含各类典中典的图片
生成有形状的词云(添加蒙版)
wordcloud对象有一个 mask参数可以设置蒙版
wordcloud(mask=’ ')
首先你得有一张白色背景,绘有形状的图片(蒙版只会将白色以外的色彩范围设置为选区)
from PIL import Image as img
import numpy as np
import wordcloud as wdc
#将图像点位转换成一组数列
ms = np.array(img.open('wyy.jpg'))
#scale设置字体的缩放尺寸,太小字体边缘会显示模糊
comment = open('wyy.txt','r',encoding='utf-8')
w = wdc.WordCloud(scale=8,font_path='simhei.ttf',mask=ms,height=1080,width=1920,background_color='white')
w.generate(comment.read())
comment.close()
w.to_file('网抑云.jpg')
![](https://img-blog.csdnimg.cn/b5cb1dc7438041efab726e25fb40a717.jpg)