介绍
python的一个生成词云的第三方库。

安装
会同时安装依赖库numpy,pillow,matplotlib等
pip install wordcloud
导入
import wordcloud
基本步骤
创建一个词云对象(或模板) —— 将文本添加到词云对象生成词云 —— 将词云图片保存到文件( —— 进一步展示词云图片)
(由于内置分词只针对英文,所以当使用汉字生成词云是需结合jieba分词使用)。
想快速开始可直接跳转示例学习
主要方法及参数
类wordcloud.WordCloud(**kwargs)
创建词云对象。
参数
字体(6)
【
font_path=None】:str。
字体文件(.otf | .ttf | .ttc)路径。默认为None,即使用模块目录下DroidSansMono.ttf字体文件。当绘制中文词云时需更改为中文字体,否则会乱码。【
min_font_size=4】:int。
词云中词的最小字体大小。当没有空间时会停止,即不一定会达到最小值,拟合完成即可。【~~max_font_size=None~~】:int or None。
词云中词的最大字体大小。默认为None,即图像高度。【
font_step=1】:int。
字体大小步长。当 >1 时,将加快算法速度,但会降低拟合度。
每个词的字体大小是根据其在字典中的顺序被依次赋予的。【
color_func=None】:function or None。
可传入(word, font_size, position, orientation, font_path, random_state)的颜色函数,可使用匿名函数,用于给词语设置颜色。 ```python —-源码—-
for word, freq in frequencies: … colors.append(self.color_func(word, font_size=font_size, position=(x, y), orientation=orientation, random_state=random_state, font_path=self.font_path))
self.layout_ = list(zip(frequencies, font_sizes, positions, orientations, colors))
<br />~~【~~`~~colormap=None~~`~~】:str or matplotlib colormap or None。~~<br />当`color_func!=None`时,使用传入的颜色函数,`colormap`被忽略。<br />当`color_func=None`时,将通过`colormap`调用`colormap_color_func(colormap)`创建颜色函数用于根据`colormap`值产生随机颜色。<br /> `colormap=None`时:<br /> `matplotlib`版本号 < 1.5,则colormap=“hsv”;<br /> `matplotlib`版本号 > 1.5,则`colormap='viridis'`<br /> `colormap`传入值时,使用传入值。<br />`colormap`作为str可传入以下参数:```pythonAccent', 'Accent_r', 'Blues', 'Blues_r', 'BrBG', 'BrBG_r', 'BuGn', 'BuGn_r', 'BuPu', 'BuPu_r', 'CMRmap', 'CMRmap_r', 'Dark2', 'Dark2_r', 'GnBu', 'GnBu_r', 'Greens', 'Greens_r', 'Greys', 'Greys_r', 'OrRd', 'OrRd_r', 'Oranges', 'Oranges_r', 'PRGn', 'PRGn_r', 'Paired', 'Paired_r', 'Pastel1', 'Pastel1_r', 'Pastel2', 'Pastel2_r', 'PiYG', 'PiYG_r', 'PuBu', 'PuBuGn', 'PuBuGn_r', 'PuBu_r', 'PuOr', 'PuOr_r', 'PuRd', 'PuRd_r', 'Purples', 'Purples_r', 'RdBu', 'RdBu_r', 'RdGy', 'RdGy_r', 'RdPu', 'RdPu_r', 'RdYlBu', 'RdYlBu_r', 'RdYlGn', 'RdYlGn_r', 'Reds', 'Reds_r', 'Set1', 'Set1_r', 'Set2', 'Set2_r', 'Set3', 'Set3_r', 'Spectral', 'Spectral_r', 'Wistia', 'Wistia_r', 'YlGn', 'YlGnBu', 'YlGnBu_r', 'YlGn_r', 'YlOrBr', 'YlOrBr_r', 'YlOrRd', 'YlOrRd_r', 'afmhot', 'afmhot_r', 'autumn', 'autumn_r', 'binary', 'binary_r', 'bone', 'bone_r', 'brg', 'brg_r', 'bwr', 'bwr_r', 'cividis', 'cividis_r', 'cool', 'cool_r', 'coolwarm', 'coolwarm_r', 'copper', 'copper_r', 'cubehelix', 'cubehelix_r', 'flag', 'flag_r', 'gist_earth', 'gist_earth_r', 'gist_gray', 'gist_gray_r', 'gist_heat', 'gist_heat_r', 'gist_ncar', 'gist_ncar_r', 'gist_rainbow', 'gist_rainbow_r', 'gist_stern', 'gist_stern_r', 'gist_yarg', 'gist_yarg_r', 'gnuplot', 'gnuplot2', 'gnuplot2_r', 'gnuplot_r', 'gray', 'gray_r', 'hot', 'hot_r', 'hsv', 'hsv_r', 'inferno', 'inferno_r', 'jet', 'jet_r', 'magma', 'magma_r', 'nipy_spectral', 'nipy_spectral_r', 'ocean', 'ocean_r', 'pink', 'pink_r', 'plasma', 'plasma_r', 'prism', 'prism_r', 'rainbow', 'rainbow_r', 'seismic', 'seismic_r', 'spring', 'spring_r', 'summer', 'summer_r', 'tab10', 'tab10_r', 'tab20', 'tab20_r', 'tab20b', 'tab20b_r', 'tab20c', 'tab20c_r', 'terrain', 'terrain_r', 'turbo', 'turbo_r', 'twilight', 'twilight_r', 'twilight_shifted', 'twilight_shifted_r', 'viridis', 'viridis_r', 'winter', 'winter_r'
图像与画布(9)
【
width=400】:int。
画布宽度(像素)。【
height=200】:int。
画布高度(像素)。【
mask=None】:nd-array or None。
指定词云图片二进制掩码,用来将单词画在上面。若指定了图片,width和height参数将被忽略,以图片数据替代。
图像中白色将被忽略,而其他颜色将被画上单词。【
background_color='black'】:color value。
词云图像的背景颜色。【~~mode='RGB'~~】:str。
默认“RGB”颜色模式。当mode='RGBA'且未设置背景颜色时,将生成透明背景。【
contour_width=0】:float。
图像轮廓宽度。当mask指定了图像,并且contour>0,将绘制图像轮廓。【
contour_color='black'】:color value。
图像轮廓颜色。【
scale=1】:float or int。
等比例缩放倍数。【~~relative_scaling='auto'~~】:float【0~1】。
根据该参数对词语进行字体大小调整, 使字体大小与frequency有关。
当repeat=True, “auto”=0, 否则”auto”=0.5。
计算:newfont_size = int(((frequency -1) relativescaling + 1) old_font_size)
old_font_size为该词按顺序本应被赋予的大小。
单词处理(10)
【
max_words=200】:int。
最大单词数。【
min_word_length=0】:int。
能包含的最短单词。【~~include_numbers=False~~】:bool。
是否包含数字。【
repeat=False】:bool。
是否重复单词或短语直到达到max_words或者min_font_size。【
stopwords=None】:set of strings or None。
淘汰单词集合。默认为None,即使用模块内置的STOPWORDS集合;如果所有单词都需要可设置为空集合。当使用generate_from_frequencies方法时,该参数被忽略。
【~~normalize_plurals=True~~】:bool。
是否去除尾随“s”。默认为True,即去除尾随“s”,并把其加入到其无尾随“s”的单词计数中,-ss结尾除外。当使用generate_from_frequencies方法时,该参数被忽略。【~~collocations=True~~】:bool。
是否包含单词搭配。当使用generate_from_frequencies方法时,该参数被忽略。【~~collocation_threshold=30~~】:int。
搭配词语必须具有比这个参数更大的搭配可能性评分才被视为搭配词。【
prefer_horizontal=0.9】:float。
水平垂直拟合次数比率。值 < 1时,如果单词不合适,将尝试旋转单词。= 1时,单词全部水平。【~~regexp=None~~】:string or None。
在process_text中将输入文本分割成tokens的正则表达式。默认为None,即使用正则表达式r"\w[\w']+"。当使用generate_from_frequencies方法时,该参数被忽略。
- 其他(2)
【~~random_state=None~~】:random.Random([seed]) or int or None。
指定一个随机数对象或随机数种子,用于生成随机数。默认为None,即使用random.Random()生成一个随机数对象。
【~~ranks_only=None~~】:。
该参数将会被删除。
方法
- 词云生成
- 【
fit_words(frequencies)==generate_from_frequencies(frequencies, max_font_size=None)】
根据单词和频数创建词云。
参数frequencies:dict(str, int)。
待生成词云的单词-词频字典。max_font_size=None:int。
该值会替换wordcloud.WordCloud(**kwargs)的max_font_size值。(建议忽略)
- 【
返回 词云对象。
- 【
process_text(text)】
根据词云对象提供的regexp,以及不绘入词云的词集合,将文本进行切割。
参数text:str
待分割文本。
返回 dict(str, int)
- 【
generate_from_text(text)==generate(text)】
从文本生成词云。内部调用process_text(text)和generate_from_frequencies(frequencies)。
参数text: str。
待生成词云的文本。
返回 词云对象。
- 【
recolor(random_state=None, color_func=None, colormap=None)】
重新着色现有布局。必须先调用generate_from_text(text)或者fit_words(frequencies)生成词云。
本质为利用colorfunc传入的函数对象更改生成的词云的[layout](#layout)属性中每个词的color值.
**参数_**~~random_state=None~~: random.Random([seed]), int, or None。
指定一个随机数对象或随机数种子,用于生成随机数,传给颜色生成函数。默认为None,即使用random.Random()生成一个随机数对象。color_func=None: function or None。
传入颜色生成函数来生成颜色。默认为None,此时如果colormap=None,则使用类WordCloud传入的颜色生成函数,否则使用colormap_color_func(colormap)创建的函数。
```python —-源码—-
self.layout = [(word_freq, font_size, position, orientation, color_func(word=word_freq[0], font_size=font_size, position=position, orientation=orientation, random_state=random_state, font_path=self.font_path)) for word_freq, font_size, position, orientation, in self.layout_]
- `~~colormap=None~~`~~: string or matplotlib colormap or None。~~<br />传给类`colormap_color_func(colormap)`来创建函数对象用来生成随机颜色,如果`color_func!=None`,该参数被覆盖。**_返回_** `词云对象`。2. 类型转换- `to_array()`<br />将词云对象图片转换为numpy数组。<br />**_返回_**<br /> `numpy数组`- 【`to_file(filename)`】<br />将词云对象转换为图片并保存为指定文件。<br />**_参数_**- `filename`: str。<br />指定保存的文件。**_返回_** `词云对象`。- `to_svg(embed_font=False, optimize_embedded_font=True, embed_image=False)`<br />**_参数_**- `embed_font=False`: bool。<br />是否在生成的SVG文件中包含字体。- `optimize_embedded_font=True`: bool。<br />是否优化字体。- `embed_image=False`: bool。<br />是否在生成的SVG文件中包含光栅化图像。对调试很有用。**_返回_** `SVG字符串`<a name="24d67862"></a>### 属性必须先调用`generate_from_text(text)` 或者 `fit_words(frequencies)`生成词云后才能访问。1. `words_`<br />返回词云对象的词语-频数`dict(str, float)`2. `[layout_](#recolor)`<br />返回每个词的`((str, float), font_size, position(x, y), orientation, rgb_color)`组成的的`列表`<a name="0775af18"></a>## ~~函数~~`~~wordcloud.random_color_func(random_state=None)~~`随机色相颜色生成,值为80%,亮度为50%,是默认的着色方法。**_参数_**- word, font_size, position, orientation, font_path<br />全部忽略。- `random_state=None`: random.Random([seed]) or None。<br />用于生成随机数。默认为None,即random.Random()**_返回_**`hsl(random_state. randint(0, 255), 80%, 50%)`**_示例_**```python---代码---# 导入import wordcloudimport random# 调用函数result = wordcloud.random_color_func(random_state=random.Random(10))# 结果print(result)---结果---hsl(16, 80%, 50%)
函数wordcloud.get_single_color_func(color)
创建一个颜色函数,该函数返回单个色调和饱和度。
参数
color: color value。
待提取色调和饱和度的颜色。
返回
`函数对象`。该函数对象需传入参数(word, font_size, position, orientation, font_path, random_state)其中`random_state=None`: random.Random([seed]) or None。函数对象返回:`rgb(r, g, b)`
示例
---代码---# 导入import wordcloudimport random# 创建函数对象rgb_func = wordcloud.get_single_color_func("black")# 调用函数对象result = rgb_func(random_state=random.Random(10))# 结果print(result)---结果---rgb(168, 168, 168)
类~~**_wordcloud.wordcloud.colormap_color_func(colormap)_**~~
从matplotlib colormap创建颜色函数。主要由recolor方法内部调用。
参数
colormap: str or matplotlib colormap。
待从中采样的颜色图。
返回
`函数对象`,该函数对象需传入参数`random_state=None`: random.Random([seed]) or None。另外还需传入四个无义位置参数,可传入None。函数对象返回:`rgb(r, g, b)`,为随机颜色。
示例
---代码---# 导入import wordcloudimport random# 创建函数对象rgb_func = wordcloud.wordcloud.colormap_color_func("Blues")# 调用函数对象result = rgb_func(None, None, None, None, random_state=random.Random(10))# 结果print(result)---结果---rgb(83, 158, 205)
示例
常用参数:
wordcloud.WordCloud(font_path=None # 设置字体width=400, # 画布宽度height=200, # 画布高度background_color="black", # 背景颜色mask=None, # 图像掩码contour_width=0, # 轮廓宽度contour_color="black", # 轮廓颜色scale=1, # 缩放倍数min_font_size=4, # 最小字体大小font_step=1, # 字体间步长color_func=None, # 颜色设置函数max_words=200, # 最大单词数min_word_length=0, # 最短单词长prefer_horizontal=0.9, # 水平垂直拟合比例,=1时单词全部水平repeat=False, # 是否重复,单词数较少时可设置重复填充图像stopwords=None, # 淘汰单词集合,当需要所有词时可设置为空集合)注:mask使用的图片尽量背景为白色,待形成词云的区域较突出。
最简单无图像词云(不修改任何参数):
# 导入import wordcloud# 词云文本en_text = """There are moments in lifewhen you miss someone so much that you just want to pick them from your dreamsand hug them for real!Dream what you want to dream;go where you want to go;be what you want to be,because you have only one lifeand one chance to do all the things you want to do."""# 创建词云对象wc = wordcloud.WordCloud()# 向词云对象添加文本wc = wc.generate(en_text)# 将词云对象保存为当前路径下的result.pngwc.to_file("./result.png")

有图像词云(重点修改mask参数添加图像)
import wordcloudimport numpy as npfrom PIL import Image# 词云文本en_text = """There are moments in lifewhen you miss someone so much that you just want to pick them from your dreamsand hug them for real!Dream what you want to dream;go where you want to go;be what you want to be,because you have only one lifeand one chance to do all the things you want to do."""# 转化指定图像:图像背景尽量为白色,图像突出mask = np.array(Image.open("./皮卡丘.jpg"))# 创建词云对象wc = wordcloud.WordCloud(mask=mask, # 图像掩码 添加了图片contour_width=1, # 轮廓宽度 轮廓宽为1contour_color="yellow", # 轮廓颜色 轮廓颜色为黄色repeat=True, # 是否重复 单词较少,重复单词以填满)# 向词云对象添加文本wc = wc.generate(en_text)# 将词云对象保存为当前路径下的result.pngwc.to_file("./result.png")


单个单词形成词云(重点需设置repeat=True,使得重复填充满)
import wordcloudimport numpy as npfrom PIL import Image# 词云文本en_text = "love"# 转化指定图像:图像背景尽量为白色,图像突出mask = np.array(Image.open("./love.jpg"))# 创建词云对象wc = wordcloud.WordCloud(mask=mask, # 图像掩码 添加了图片repeat=True, # 是否重复 单词较少,重复单词以填满)# 向词云对象添加文本wc = wc.generate(en_text)# 将词云对象保存为当前路径下的result.pngwc.to_file("./result.png")


给所有单词指定同一种颜色(重点修改color_func参数)
需安装第三方模块webcolors:pip install webcolors,也可通过其他方式将颜色字符串转变为rgb值。
import wordcloudimport numpy as npfrom PIL import Imageimport webcolors #用于颜色转换的函数# 词云文本en_text = """There are moments in lifewhen you miss someone so much that you just want to pick them from your dreamsand hug them for real!Dream what you want to dream;go where you want to go;be what you want to be,because you have only one lifeand one chance to do all the things you want to do."""# 转化指定图像:图像背景尽量为白色,图像突出mask = np.array(Image.open("./love.jpg"))# 创建词云对象wc = wordcloud.WordCloud(mask=mask, # 图像掩码 添加了图片contour_width=1, # 轮廓宽度 轮廓宽为1contour_color="red", # 轮廓颜色 轮廓颜色为红色color_func=lambda *word, **kwargs: webcolors.name_to_rgb("red"), # 颜色设置函数 使用匿名函数设置所有单词为红色repeat=True, # 是否重复 单词较少,重复单词以填满prefer_horizontal=1, # 水平垂直拟合比例,=1时单词全部水平)# 向词云对象添加文本wc = wc.generate(en_text)# 将词云对象保存为当前路径下的result.pngwc.to_file("./result.png")

给指定单词指定颜色(重点修改color_func参数)
import wordcloudimport numpy as npfrom PIL import Imageimport webcolors# 词云文本en_text = """There are moments in lifewhen you miss someone so much that you just want to pick them from your dreamsand hug them for real!Dream what you want to dream;go where you want to go;be what you want to be,because you have only one lifeand one chance to do all the things you want to do."""# 建立颜色-词语字典color_words = {"red":['moments', 'life'], # 红色"green":['miss','someone', 'much'], # 绿色"blue":['want', 'pick'], # 蓝色"yellow":['hug', 'real', 'dream', 'go', 'one', 'chance', 'things'], # 其他黄色}# 转化为词语-颜色字典word_color = {}for color, words in color_words.items():for word in words:word_color[word] = color"""{'moments': 'red','life': 'red','miss': 'green','someone': 'green','much': 'green','want': 'blue','pick': 'blue','hug': 'yellow','real': 'yellow','dream': 'yellow','go': 'yellow','one': 'yellow','chance': 'yellow','things': 'yellow'}"""# 转化指定图像:图像背景尽量为白色,图像突出mask = np.array(Image.open("./皮卡丘.jpg"))# 创建词云对象wc = wordcloud.WordCloud(mask=mask, # 图像掩码 添加了图片contour_width=1, # 轮廓宽度 轮廓宽为1contour_color="yellow", # 轮廓颜色 轮廓颜色为黄色repeat=True, # 是否重复 单词较少,重复单词以填满color_func=lambda *word, **kwargs: webcolors.name_to_rgb(word_color[word[0]]), # 颜色设置函数 使用匿名函数设置)# 向词云对象添加文本wc = wc.generate(en_text)# 将词云对象保存为当前路径下的result.pngwc.to_file("./result.png")

中文词云(重点更改font_path参数,同时注意处理中文文本)
import wordcloudimport numpy as npfrom PIL import Imageimport jieba# 词云文本zh_text = """不要在本该奋斗的年纪选择了安逸,只有度过了一段连自己都被感动的日子,才会遇见那个最好的自己,未来的你,一定会感谢现在拼命努力的自己。永远相信,越努力,越幸运,所有失去的,都会以另一种方式归来,踏实一些,你想要的,岁月统统都会给你。"""# 处理文本,去除中文标点,词语间以空格分开(必需)zh_words = jieba.lcut(zh_text)for i in zh_words:if i in "\n。,":for n in range(zh_words.count(i)):zh_words.remove(i)zh_words = " ".join(zh_words) # 必需处理为空格分隔的词语字符串,类似英文"""不要 在 本该 奋斗 的 年纪 选择 了 安逸 只有 度过 了 一段 连 自己 都 被 感动 的 日子 才 会 遇见 那个 最好 的 自己 未来 的 你 一定 会 感谢 现在 拼命 努力 的 自己 永远 相信 越 努力 越 幸运 所有 失去 的 都 会 以 另 一种 方式 归来 踏实 一些 你 想要 的 岁月 统统 都 会 给 你"""# 转化指定图像:图像背景尽量为白色,图像突出mask = np.array(Image.open("./皮卡丘.jpg"))# 创建词云对象wc = wordcloud.WordCloud(repeat=True, # 是否重复 单词较少,重复单词以填满font_path="msyh.ttc", # 设置为中文支持的字体(必需))# 向词云对象添加文本wc = wc.generate(zh_words)# 将词云对象保存为当前路径下的result.pngwc.to_file("./result.png")

