#!/usr/bin/env python
"""Colored by Group Example
========================
Generating a word cloud that assigns colors to words based on
a predefined mapping from colors to words
基于颜色到单次的映射,将颜色分配给单次,生成词云。"""
from wordcloud import(WordCloud, get_single_color_func)importmatplotlib.pyplot as pltclassSimpleGroupedColorFunc(object):"""Create a color function object which assigns EXACT colors
to certain words based on the color to words mapping
创建一个颜色函数对象,它根据颜色到单词的映射关系,为单词分配精准的颜色。
Parameters
参数
----------
color_to_words : dict(str -> list(str))
A dictionary that maps a color to the list of words.
default_color : str
Color that will be assigned to a word that's not a member
of any value from color_to_words."""
def __init__(self, color_to_words, default_color):
self.word_to_color={word: colorfor (color, words) incolor_to_words.items()for word inwords}
self.default_color=default_colordef __call__(self, word, **kwargs):returnself.word_to_color.get(word, self.default_color)classGroupedColorFunc(object):"""Create a color function object which assigns DIFFERENT SHADES of
specified colors to certain words based on the color to words mapping.
Uses wordcloud.get_single_color_func
Parameters
----------
color_to_words : dict(str -> list(str))
A dictionary that maps a color to the list of words.
default_color : str
Color that will be assigned to a word that's not a member
of any value from color_to_words."""
def __init__(self, color_to_words, default_color):
self.color_func_to_words=[
(get_single_color_func(color), set(words))for (color, words) incolor_to_words.items()]
self.default_color_func=get_single_color_func(default_color)defget_color_func(self, word):"""Returns a single_color_func associated with the word"""
try:
color_func=next(
color_funcfor (color_func, words) inself.color_func_to_wordsif word inwords)exceptStopIteration:
color_func=self.default_color_funcreturncolor_funcdef __call__(self, word, **kwargs):return self.get_color_func(word)(word, **kwargs)#text是要分析的文本内容
text = """The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!"""
#Since the text is small collocations are turned off and text is lower-cased
wc = WordCloud(collocations=False).generate(text.lower())#自定义所有单词的颜色
color_to_words ={#words below will be colored with a green single color function
'#00ff00': ['beautiful', 'explicit', 'simple', 'sparse','readability', 'rules', 'practicality','explicitly', 'one', 'now', 'easy', 'obvious', 'better'],#will be colored with a red single color function
'red': ['ugly', 'implicit', 'complex', 'complicated', 'nested','dense', 'special', 'errors', 'silently', 'ambiguity','guess', 'hard']
}#Words that are not in any of the color_to_words values#will be colored with a grey single color function#不属于上述设定的颜色词的词语会用灰色来着色
default_color = 'grey'
#Create a color function with single tone#grouped_color_func = SimpleGroupedColorFunc(color_to_words, default_color)
#Create a color function with multiple tones
grouped_color_func =GroupedColorFunc(color_to_words, default_color)#Apply our color function#如果你也可以将color_func的参数设置为图片,详细的说明请看 下一部分
wc.recolor(color_func=grouped_color_func)#画图
plt.figure()
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()