您的位置:首页 > 其它

wordcloud词云模块

2020-05-11 04:13 721 查看

安装

pip3 install wordcloud

WordCloud类参数解析

  • font_path:otf或ttf路径,默认使用DroidSansMono。windows可使用自带字体,在C盘Font目录下,无
  • width :画布宽度,默认400
  • height :画布高度,默认200
  • prefer_horizontal : 词条水平显示的比例
  • mask : 遮罩,nd-array类型,指定此参数时画布尺寸将调整至与遮罩相同,词云只会绘制在遮罩图片非白色的区域。
  • contour_width: 遮罩的轮廓线宽度
  • contour_color: 遮罩的轮廓线颜色
  • scale : 计算完成后图片的缩放比例
  • min_font_size : 最小字体,计算将在没有足够空间容纳此字体时停止,默认为4
  • font_step : 字体跨度,默认为1。大于1会加速计算,但结果不够美观
  • max_words : 最大词数,默认200
  • stopwords : 停用词,不计入词频
  • background_color : 背景颜色,默认黑色
  • max_font_size : 最大字体尺寸,默认为图片高度
  • mode : 图片模式,默认为RGB。如果设为RGBA且背景色为空,则背景透明
  • relative_scaling : 词条间相对比例。设为0时只有词条的词频排名被考虑,设为1时词条尺寸将与词频比例一致。默认为auto,auto默认为0.5,如果repeat参数设为True,则该值设为0。
  • color_func : 上色函数,覆盖colormap
  • regexp : 切分句子提取词语的正则表达式
  • collocations : 是否包含词语搭配
  • colormap : 颜色地图,默认为绿色。颜色大全https://matplotlib.org/users/colormaps.html
  • normalize_plurals : 是否标准化复数,默认为True。以s结尾的数的词频加在其单数形式上,忽略以ss结尾的词
  • repeat : 重复直至最大词数或最小字号
  • include_numbers : 是否将数字计入词频
  • min_word_length : 词条最少字数

WordCloud类常用方法

  • fit_words(self, frequencies) : 利用词频创建词云,词频字典作为参数
  • to_image(self) : 输出PIL.Image对象
  • recolor(self, random_state=None, color_func=None, colormap=None) : 重新上色
  • to_file(self, filename) : 输出文件

其他常用类

  • wordcloud.ImageColorGenerator(image) : 根据图片的nd-array生成上色函数

自订词云类

"""绘制词云"""
from io import BytesIO

import requests
import numpy as np
from PIL import Image
from wordcloud import WordCloud, ImageColorGenerator

class ImgWordCloud(WordCloud):
"""根据图片绘制词云"""

def __init__(self, font_path='simkai.ttf', mode='RGBA', background_color=None, **kwargs):
super(ImgWordCloud, self).__init__(font_path=font_path, mode=mode, background_color=background_color, **kwargs)

def load_img(self, template_img, img_scale=1.0, set_transparency=None):
"""
加载遮罩图片
:param template_img: 样式图片,可为文件路径或url,若未指定则输出默认矩形
:param img_scale: 原始图片尺寸缩放,影响生成图片的尺寸。与类参数的scale不同,该参数不会同时放大字体
:param set_transparency: black/white,设置图片的黑色/白色为透明
"""
if template_img.startswith('http'):
content = requests.get(template_img).content
bytes_io = BytesIO(content)
else:
bytes_io = open(template_img, 'rb')
img = Image.open(bytes_io)
width, height = img.size
img = img.resize((int(width * img_scale), int(height * img_scale)))
pic_mat = np.array(img)
mask = pic_mat.copy()
if set_transparency == 'black':
mask[mask.sum(axis=2) < 45] = 255
elif set_transparency == 'white':
mask[mask.sum(axis=2) > 720] = 255
self.mask = mask
self.color_func = ImageColorGenerator(pic_mat)

def generate_from_frequency_file(self, frequency_file, output_image=None, **img_kwargs):
"""
根据词频文件生成词云
:param frequency_file:词频文件,逗号分隔,格式为 “词语,频率”
:param output_image: 输出图片,若未指定则直接显示
:param img_kwargs: 图片参数
:return: None
"""
with open(frequency_file, encoding='utf8')as file:
word_freq = {row.split(',')[0]: float(row.split(',')[1]) for row in file.read().splitlines()}
if img_kwargs:
self.load_img(**img_kwargs)
self.fit_words(word_freq)
self.export_img(output_image)

def generate_char_img(self, char, output_image=None, **img_kwargs):
"""
根据字符填充图片
:param char:填充字符
:param output_image: 输出图片,若未指定则直接显示
:param img_kwargs: 图片参数
:return: None
"""
self.repeat = True
self.max_font_size = 10
self.max_words = 10000
self.relative_scaling = 0
if img_kwargs:
self.load_img(**img_kwargs)
self.fit_words({char: 1})
self.export_img(output_image)

def export_img(self, output_img):
"""
导出图片
:param output_img: 输出图片,若未指定则直接显示
"""
if output_img:
self.to_file(output_img)
else:
self.to_image().show()

if __name__ == '__main__':
word_cloud = ImgWordCloud()
word_cloud.generate_char_img(
char='*',
template_img=r"C:\Users\hmy\Pictures\90sheji_linggan_13469597.png",
# output_image='result.png',
set_transparency='white'
)
# word_cloud.generate_from_frequency_file(
#     frequency_file=r'C:\Users\hmy\Documents\PycharmProjects\Test\test.csv',
#     template_img=r"C:\Users\hmy\Pictures\90sheji_linggan_13469597.png",
#     # output_image='result.png',
#     set_transparency='white',
#     # img_scale=1
# )

效果预览:

jerrism 原创文章 16获赞 1访问量 456 关注 私信
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: