Implementation of Python WordCloud Tone Modification

  • 2021-09-20 21:04:43
  • OfStack

When drawing the word cloud picture, it is found that some words are yellow, which leads to the inability to see clearly. Therefore, it is necessary to modify the hue of the whole word cloud picture to cool hue

Specifically speaking

The color_func parameter in wordcloud allows us to customize the color function


def random_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None):
    h = randint(120,250)
    s = int(100.0 * 255.0 / 255.0)
    l = int(100.0 * float(randint(60, 120)) / 255.0)
    return "hsl({}, {}%, {}%)".format(h, s, l)

h represents the value range of colors. We can view the value of h corresponding to the value range of each color by Google colour picker

Here the blogger takes the blue-green so the range of h is between 120 and 250. You can modify it yourself

Finally, set in the parameters color_func = random_color_func You can

Supplement: The method of changing the word cloud generated by wordcloud library into unified 1 color in python

Looking for more than an hour on the Internet, I didn't find a way. I didn't find an operation method to see wordcloud official website. I simply looked at the source code directly

Then copy a small piece of code from it:


color_func=lambda *args, **kwargs: "red"

Assign this code and parameter 1 such as font to the word cloud variable, as follows:


w=wordcloud.WordCloud(font_path='msyh.ttc',mask=mianju,\
  width=1000,height=700,background_color='white',mode='RGBA',color_func=lambda *args, **kwargs: "red")

The following is the complete code, and the pictures and text documents with the corresponding names are put into one


import jieba
import wordcloud
import imageio
zhezhao=imageio.imread(' Picture mask .jpg')# Use imageio The replacement has now been removed image Adj. scipy Library 
f=open(' This is 1 Text .txt','r',encoding='utf-8')
t=f.read()
f.close()
ls=jieba.lcut(t)
txt=' '.join(ls)
w=wordcloud.WordCloud(font_path='msyh.ttc',mask=zhezhao,\
  width=1000,height=700,background_color='white',mode='RGBA',color_func=lambda *args, **kwargs: "red")
w.generate(txt)
w.to_file(' This is the generated picture .png')

Related articles: