WordCloud(词云)的简单运用


WordCloud

WordCloud 是一款python环境下的词云图工具包,同时支持python2和python3,能通过代码的形式把关键词数据转换成直观且有趣的图文模式。

主要参数

属性

数据类型|默认值

解析

font_path

string

字体路径windows:C:/Windows/Fonts/Linux: /usr/share/fonts

width

int (default=400)

输出的画布宽度,默认为400像素

height

int (default=200)

输出的画布高度,默认为200像素

prefer_horizontal

float (default=0.90)

词语水平方向排版出现的频率,默认 0.9 所以词语垂直方向排版出现频率为0.1

mask

nd-array or None(default=None)

如果参数为空,则使用二维遮罩绘制词云如果mask非空,设置的宽高值将被忽略遮罩形状被 mask 取代

scale

float (default=1)

按照比例进行放大画布,如设置为1.5则长和宽都是原来画布的1.5倍

min_font_size

int (default=4)

显示的最小的字体大小

font_step

int (default=1)

字体步长,如果步长大于1,会加快运算但是可能导致结果出现较大的误差

max_words

number (default=200)

要显示的词的最大个数

stopwords

set of strings or None

设置需要屏蔽的词,如果为空,则使用内置的STOPWORDS

background_color

color value default=”black”

背景颜色

max_font_size

int or Nonedefault=None

显示的最大的字体大小

mode

string (default=”RGB”)

当参数为“RGBA”并且background_color不为空时,背景为透明

relative_scaling

float (default=.5)

词频和字体大小的关联性

color_func

callable, default=None

生成新颜色的函数,如果为空,则使用 self.color_func

regexp

string or None (optional)

使用正则表达式分隔输入的文本

collocations

bool, default=True

是否包括两个词的搭配

colormap

string or matplotlib colormapdefault=”viridis”

给每个单词随机分配颜色,若指定color_func,则忽略该方法

random_state

int or None

为每个单词返回一个PIL颜色

简单实例

代码示例

 1 from wordcloud import WordCloud
 2 import numpy as np
 3 from PIL import Image   # PIL图像处理库
 4 # 设置参数
 5 wcd=WordCloud(background_color="white",colormap="Reds",  # 设置背景颜色为白色,词云颜色主色调为红色
 6               contour_width=8,contour_color="Red",repeat=True, # 设置边线为8,颜色为红,repeat为true表示词语允许重复
 7               max_words=100,height=480,width=854,max_font_size=100, # 最大单词数100,图高480,宽854,字体尺寸100
 8               font_path="font/msyh.ttc",mask=np.array(Image.open("ChinaMap.png"))) # 设置字体路径,mask为词云轮廓
 9 
10 text="富强、民主、文明、和谐,自由、平等、公正、法治,爱国、敬业、诚信、友善."
11 wcd.generate(text)   # 读取文本文件
12 wcd.to_file("images5.png")  # 保存为图片

效果图

 

更多示例

https://github.com/amueller/word_cloud/blob/master/examples/a_new_hope.py