目录
传入colormap
这种方式只需在WordCloud初始化时传入colormap即可
wc=wordcloud.WordCloud(font_path=r"C:\Windows\Fonts\simhei.ttf",#字体路径
colormap="spring")
colormap 的名称 可以在官方查到 matplotlibcolormaps
传入color_func
单颜色函数
可以使用wordcloud中的 get_single_color_func(color)
color 可以是 颜色字符串 "red"、"green"、"blue".....
也可以是用字符串表示的十六进制rgb 比如 "#ff0000" 表示红色
wc=wordcloud.WordCloud(font_path=r"C:\Windows\Fonts\simhei.ttf",#字体路径
color_func=wordcloud.get_single_color_func("blue"))
自定义颜色函数
可以通过函数回调自定义颜色函数
该函数必须传入相应的的参数
color_func(word=None, font_size=None, position=None,
orientation=None, font_path=None, random_state=None)
word 是单个分词
font_size 词的字号
position 词所在的位置
orientation 表示该词是横向还是竖向 (None 为横向 2为竖向)
font_path 字体路径
random_state Random类的实例
需返回一个rgb元组 return (255,0,255)
代码
#python 版本3.9.4
import wordcloud
import jieba
import imageio
#读取形状图片(足球)
image=imageio.imread("wordimage.jpg")
data=(file:=open("datajieba.txt",'r',encoding="utf8")).read()
file.close()
#将停用词添加到冻结集合
stopwords=frozenset(((
file:=open("stopwords.txt",'r',encoding="utf8")).read()).split())
file.close()
#根据字体属性更改颜色
def color_func(word,/,font_size,position,random_state,**kwargs):
#字体位置 y
if position[0]<500:
r=random_state.randint(0,40)# 相当于random.randint(0,40)
else:
r=random_state.randint(100,150)
#字体位置 x
if position[1]<500:
g=random_state.randint(0,40)
else:
g=random_state.randint(100,150)
#字体大小
if font_size<50:
b=random_state.randint(0,40)
else:
b=random_state.randint(100,150)
#返回一个rgb颜色元组
return (r,g,b)
wc=wordcloud.WordCloud(font_path=r"C:\Windows\Fonts\simhei.ttf",#字体路径
min_font_size=6,max_font_size=100, #字号
mask=image,#词云形状
color_func=color_func,# 这里要将刚才写的函数传入
font_step=4, #字号步长
max_words=500, #最大词数
background_color="white")#背景色
filterfunc=lambda x:x not in stopwords and len(x)>1
# 将停用词以及长度为1的字去除
words=filter(filterfunc, jieba.cut(data,HMM=True))
#生成词云
wc.generate(' '.join(words))
#生成图片
wc.to_file("pywordcloud.png")
效果
源码在此 链接:https://pan.baidu.com/s/1u3BcBWgGGGmIrk-1YaQ0Og
提取码:word