python 定制个性化词云(根据图片自动生成形状和颜色) |
您所在的位置:网站首页 › spyder词云 › python 定制个性化词云(根据图片自动生成形状和颜色) |
python 定制个性化词云(根据图片自动生成形状和颜色)
整体介绍
话不多说先上成品图: 1、jieba:中文分词库 2、wordcloud:生成词云 3、imageio:读取图像数据 二、代码详细展示2.1 准备工作 #引入需要的库 import jieba import imageio import wordcloud #用imageio的imread函数读取图片,在生成词云的时候将他设置为mask参数(形状)的值 mask1=imageio.imread("C:/Users/Administrator.DESKTOP-L29CIOJ/Desktop/xinpict.png")#读取背景图片2.2 #打开从qq里面导出的聊天记录,除去时间,名称等不相关的段落 #以删除2020-XX-XX所在行为例 with open("C:/Users/Administrator.DESKTOP-L29CIOJ/Desktop/xin1.txt","r",encoding="UTF-8") as r:#打开聊天记录文件,按行读取 lines=r.readlines() with open("C:/Users/Administrator.DESKTOP-L29CIOJ/Desktop/xin1.txt", "w",encoding="UTF-8") as w:#删除不需要的行 for line in lines: if "2020-" not in line: w.write(line) r.close() w.close()文件展示 2.3 用jieba库对聊天记录进行分词,得到聊天中的众多关键词 f=open("C:/Users/Administrator.DESKTOP-L29CIOJ/Desktop/xin1.txt","r",encoding="UTF-8")#打开处理好的聊天记录文件 t=f.read() f.close() ls=jieba.lcut(t) #用lcut函数进行分词 txt="".join(ls) #用空格将关键词隔开2.4 用wordcloud生成词云 image_colors = wordcloud.ImageColorGenerator(mask1)#利用ImageColorGenerator函数将词云的颜色参数设置为根据图片颜色确定 w=wordcloud.WordCloud(font_path="msyh.ttc",width=800,height=200,mask=mask1,background_color="white",max_words=100000,color_func=image_colors,max_font_size=60) #设置词云的参数,记住将提到的形状参数设为上面生成的mask1,颜色参数设为image_colors w.generate(txt)#生成词云 w.to_file("love2.png")#图片保存为love2.png(注意位置在你的程序文件夹里头)over |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |