!文章内容如有错误或排版问题,请提交反馈,非常感谢!
Wordcloud 是一个生成词云的 Python 包,可以以词语为基本单位更加直观和艺术的展示文本,呈现效果类似标签云。这里主要讲解下如何使用。
wordcloud 使用文档
所有函数均封装在 WordCloud 类里:
- WordCloud([…]) 生成并绘制 WordCloud 对象
- ImageColorGenerator(image) 词云颜色生成器(基于图片颜色)
- random_color_func([]) 词云颜色随机生成
wordcloud.WordCloud
class wordcloud.WordCloud(font_path=None, width=400, height=200, margin=2, ranks_only=None, prefer_horizontal=0.9, mask=None, scale=1, color_func=None, max_words=200, min_font_size=4, stopwords=None, random_state=None, background_color='black', max_font_size=None, font_step=1, mode='RGB', relative_scaling=0.5, regexp=None, collocations=True, colormap=None, normalize_plurals=True)
参数:
- font_path: string 需要使用的字体路径(支持 OTF 和 TTF)。英文可以不进行设置,如果要呈现中文,则必须设置为中文字体,否则会显示乱码。
- width: int (default=400) 画布的宽度。
- height: int (default=200) 画布的高度。
- prefer_horizontal: float (default=0.90) 尝试水平摆放字体和垂直摆放字体的比例,若 prefer_horizontal<1,当摆放不合适的时候,算法将尝试旋转单词。目前没有内置的方法来获取垂直单词
- mask: nd-array or None (default=None) 背景图形,如果想根据图片绘制,则需要设置
- scale: float (default=1) 计算值和绘图之间的缩放比例。对于大型文字云图像,使用缩放而不是较大的画布尺寸要快得多,但可能导致较粗糙的文字。
- min_font_size: int (default=4) 使用最小的字体大小。当没有更多的空间时停止绘制。
- font_step: int (default=1) 字体的步长。font_step>1 时可能会加快计算速度,但会导致糟糕的字体适应性布局。
- max_words: number (default=200) 单词的最大数目。
- stopwords: set of strings or None 停用词集合,这些词将被忽略。如果没有,则将使用内置的 STOPWORDS 列表。
- background_color: color value (default=”black”) 词云图像的背景颜色。
- max_font_size: int or None (default=None) 使用的最大字体大小。默认使用图像的高度。
- mode: string (default=”RGB”) 当模式为“RGBA”且 background_color 为 None 时,会生成透明背景。
- relative_scaling: float (default=.5) 字体大小的相对单词频率的重要性。relative_scaling=0 时,只考虑单词等级。使用 relative_scaling=1 时,频繁两倍的单词将具有两倍的大小。如果你想考虑单词的频率,而不仅仅是他们的等级,那么 5 左右的 relative_scaling 通常看起来不错。
- color_func: callable, default=None 可用参数关键字 font_size, position, orientation, font_path, random_state 调用,它为每个单词返回一个 PIL 颜色。覆盖”colormap”。请参阅 colormap 来指定 matplotlib 的颜色映射。
- regexp: string or None (optional) 正则表达式将输入文本拆分为待处理文本中的标记。如果指定 None,则使用 r“\w[\w’]+”。
- collocations: bool, default=True 是否包含两个词的搭配(bigrams),默认为 True。
- colormap: string or matplotlib colormap, default=”viridis”matplotlib 色图,可更改名称进而更改整体风格
- Matplotlib 色彩映射表为每个单词随机绘制颜色。如果指定了“color_func”,则忽略。
- normalize_plurals: bool, default=True 是否从文字中删除“尾随”。如果为真,当出现以’s’结尾的单词,则以’s’结尾的单词将被删除,并将其计数添加到没有’s’结尾的版本,以’ss’结尾的单词被忽略。
注意:较大的画布使代码明显变慢。如果您需要较大的单词云,请尝试较小的画布大小,然后设置缩放参数。根据最大字体大小和缩放启发式算法,相比单词实际出现的频率,算法可能会给单词的等级更多的权重。
初始化实例(默认值):
__init__(font_path=None, width=400, height=200, margin=2, ranks_only=None, prefer_horizontal=0.9, mask=None, scale=1, color_func=None, max_words=200, min_font_size=4, stopwords=None, random_state=None, background_color='black', max_font_size=None, font_step=1, mode='RGB', relative_scaling=0.5, regexp=None, collocations=True, colormap=None, normalize_plurals=True)
属性:
- words_ (dict of string to float) 单词标识对应其出现次数,如{‘hello’:90,’good’:30}..versionchanged:2.0 words_: 现在是一个字典
- layout_ (list of tuples (string, int, (int, int), int, color))) 编码拟合词云,为每个单词编码字符串,字体大小,位置,方向和颜色。
方法:
- fit_words(frequencies) 根据单词和频率创建一个 word_cloud。别名为 generate_from_frequencies。参数: frequencies: array of tuples 元组包含单词及其频率。Note: 最新版已经改为字典了。
- generate_from_frequencies(frequencies, max_font_size=None) 根据单词和频率创建词云。参数: frequencies: dict from string to float 字典包含单词及其频率。max_font_size: int 使用此最大字体大,而不是 max_font_size
- generate(text) 从文本生成 wordcloud。别名 generate_from_text。实际调用 process_text 和 generate_from_frequencies。
- generate_from_text(text) 从文本生成 wordcloud。实际调用 process_text 和 generate_from_frequencies。
- process_text(text) 将长文本拆分为单词,去除停用词(敏感词)。
- recolor(random_state=None, color_func=None, colormap=None) 重新着色现有布局。
- to_array() 转换为 numpy 数组。词云图像作为 numpy 矩阵。
- to_file(filename) 导出为图像文件。
wordcloud.ImageColorGenerator
class wordcloud.ImageColorGenerator(image) 基于彩色图像的颜色生成器。根据 RGB 图像生成颜色。一个单词将使用彩色图像中包围矩形的平均颜色进行着色。构造完成后,该对象充当可调用对象,可以将其作为 color_func 传递给 WordCloud 类的构造函数或 recolor 这个重新着色方法。
参数:
- image: n 维矩阵, shape (height, width, 3) 用于生成文字颜色的图像。Alpha 通道被忽略。对于 wordcloud 实例,这应该和画布大小相同。
wordcloud.random_color_func
wordcloud.random_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None) 随机色调颜色生成。默认着色方法。这只是随机选择一个值为 80% 和光照 50% 的色调。
参数:
- word, font_size, position, orientation: ignored.
- random_state: random.Random object or None, (default=None) 如果给定了一个随机对象,则用它来生成随机数。
Wordcloud 实战:基于 tf-idf 生成词云
网上的很多文章都是基于词频生成词云,这里来进一步实践通过 tf-idf 生成词云,让”关键词”更加突出。
1、使用词频方式生成词云
import jieba from collections import Counter from wordcloud import WordCloud import matplotlib.pyplot as plt with open("data/2019年国务院政府工作报告.txt", encoding="utf-8") as f: content = f.read() with open("data/CNENstopwords.txt", encoding="utf-8") as f: stopwords = f.read() text = jieba.cut(content) new_text = [] for w in text: if w not in stopwords: new_text.append(w) counter = Counter(new_text) wordcloud = WordCloud(font_path="font/FZYingXueJW.TTF", background_color="white", width=800, height=600) wordcloud.generate_from_frequencies(dict(counter.most_common(50))) plt.imshow(wordcloud, interpolation="bilinear") plt.axis("off") plt.show()
2、使用 tf-idf 方式生成词云
import jieba.analyse from wordcloud import WordCloud import matplotlib.pyplot as plt with open("data/2019年国务院政府工作报告.txt", encoding="utf-8") as f: content = f.read() tags = jieba.analyse.extract_tags(content, topK=50, withWeight=True) wordcloud = WordCloud(font_path="font/FZYingXueJW.TTF", background_color="white", width=800, height=600) wordcloud.generate_from_frequencies(dict(tags)) plt.imshow(wordcloud, interpolation="bilinear") plt.axis("off") plt.show()
从上面两张图可以看到两者还是存在很大的区别的。
参考链接: