带有自定义随机颜色生成的python中的词云

Osh*_*twa 4 python colors word-cloud

我看到这个功能可以在线生成词云,但是我无法弄清楚如何更改def_random_func. 假设我想要橙色,现在代码总是生成绿色的词云。这是代码:

import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS

def random_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None):
    h = int(360.0 * 45.0 / 255.0)
    s = int(100.0 * 255.0 / 255.0)
    l = int(100.0 * float(random_state.randint(60, 120)) / 255.0)

    return "hsl({}, {}%, {}%)".format(h, s, l)

file_content = open("rr.txt").read()
wordcloud = WordCloud(font_path=r'C:\Windows\Fonts\Verdana.ttf',
                      stopwords=STOPWORDS,
                      background_color='white',
                      width=1200,
                      height=1000,
                      color_func=random_color_func
                      ).generate(file_content)

plt.imshow(wordcloud)
plt.axis('off')
plt.show()
Run Code Online (Sandbox Code Playgroud)

Mar*_*ans 11

random_color_func()是创建相同色调但具有不同亮度的颜色。你只需要决定你想要哪种色调。因此,对于橙色,您可以考虑使用 值21,例如:

def random_color_func(word=None, font_size=None, position=None,  orientation=None, font_path=None, random_state=None):
    h = int(360.0 * 21.0 / 255.0)
    s = int(100.0 * 255.0 / 255.0)
    l = int(100.0 * float(random_state.randint(60, 120)) / 255.0)

    return "hsl({}, {}%, {}%)".format(h, s, l)
Run Code Online (Sandbox Code Playgroud)

色调值在范围内0-360,您可以使用在线颜色选择器找到合适的值(例如尝试使用谷歌搜索颜色选择器)。该代码只是从0-255另一个通用标准的范围转换而来。因此,与其进行转换,不如让h = 30.

这会给你类似的东西:

橙色文字云

您可以更改 randint 范围以使其更亮。