词云(WordCloud)

WordCloud的参数:

  • font_path:可用于指定字体路径
  • width:词云的宽度,默认为 400;
  • height:词云的⾼度,默认为 200;
  • mask:蒙版,可⽤于定制词云的形状;
  • min_font_size:最⼩字号,默认为 4;
  • max_font_size:最⼤字号,默认为词云的⾼度;
  • max_words:词的最⼤数量,默认为 200;
  • stopwords:将被忽略的停⽤词,若不指定则使⽤默认停⽤词词库;
  • background_color:背景颜⾊,默认为 black;
  • mode:默认为RGB模式,如果为RGBA模式且background_color设 为 None,则背景将透明。
  • generate(str) 接受一个字符串

生成一个词云只需要:

wc  = WordCloud().generate(text)
plt.imshow(wc, interpolation='bilinear')
# 打开文本
text = open(base_dir + 'constitution.txt').read()
# 生成对象
wc  = WordCloud().generate(text)

# 显示
plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.show()

wc.to_file("默认样式.png")

自定义字体

wc = WordCloud('Hiragino.ttf')

使用中文

# 分词
text_new = " ".join(jieba.cut(text))
wc = WordCloud('Hiragino.ttf') # 不加字体会中文乱码

使用蒙版,

透明背景: mode='RGBA', background_color=None

mask = np.array(Image.open("black_mask.png"))
wc = WordCloud(font_path='Hiragino.ttf', mode='RGBA', background_color=None, mask=mask, width=600, height=400)

使用图片(蒙版)中的颜色

image_colors = ImageColorGenerator(mask)
wc.recolor(color_func=image_colors)

自定义颜色函数

# 颜色函数
def random_color(word, font_size, position, orientation, font_path, random_state):
	s = 'hsl(0, %d%%, %d%%)' % (random.randint(60, 80), random.randint(60, 80))
	return s
...

wc = WordCloud(color_func=random_color, font_path='Hiragino.ttf',mode='RGBA', background_color=None, mask=mask)

使用权重

# 提取关键词和权重
freq = jieba.analyse.extract_tags(text_new, topK=200, withWeight=True)   # 列表
freq = {i[0]: i[1] for i in freq}    # 字典

mask = np.array(Image.open(f"{base_dir}color_mask.png"))
wc = WordCloud(font_path='Hiragino.ttf',mode='RGBA', background_color=None, mask=mask)
res = wc.generate_from_frequencies(freq)

也可以使用:

freq = nltk.FreqDist(word_text)
# wc.fit_words(freq)    # 然后再generate
wc.generate_from_frequencies(freq)

输出

  • 提供了四个输出函数:
    1. to_array(self):numpy数组格式
    2. to_file(self, filename)
    3. to_html(self):没有实现
    4. to_image(self):PIL图像

依赖的包如下:

from wordcloud import WordCloud
from wordcloud import ImageColorGenerator
import matplotlib.pyplot as plt
import jieba
import jieba.analyse
from PIL import Image
import random
import numpy as np
原文地址:https://www.cnblogs.com/twilight0402/p/13384483.html