【Python例】利用 python 进行用户画像词云图的生成 --- wordcloud


【Python例】利用 python 进行用户画像词云图的生成 — wordcloud

本文主要用于记录,并使用 python 脚本进行用户画像的词云图的生成。

前言

对于词云图来说,是一个用户画像数据可视化的工具,可以较为形象的表示用户的特征信息,可以为一些场景做一个数据的定性观察,下面介绍基于python的wordcloud工具进行词云的数据可视化。

基本文件

  1. 词云图基本描述文本
  2. 词云图背景基本图片
  3. 词语分割库 jieba
  4. 科学计算库 nump
  5. 数据可视化分析库 matplotlib
  6. 词云库 wordcloud

使用以下代码进行安装:

pip install numpy
pip install matplotlib
pip install jieba
pip install wordcloud

Python 脚本源码

#!/usr/bin/env python3

# 词云图
# pip install numpy
# pip install matplotlib
# pip install jieba
# pip install wordcloud

from wordcloud import WordCloud, ImageColorGenerator, STOPWORDS  # 词云,颜色生成器,停止词
import jieba  # 词语切割
import matplotlib.pyplot as plt  # 数据可视化
from PIL import Image  # 处理图片
import numpy as np  # 科学计算
import os

# print(os.getcwd())
current_path = os.path.dirname(__file__)  # 设置相对路径
# print(current_path)

path_txt = ''  # 文本路径
path_bg = ''  # 词云背景模板路径
font_path = "/System/Library/Fonts/PingFang.ttc"  # 设置字体,可以显示中文
file = open(current_path+'/source/text_word.txt', 'r', encoding='utf-8')
text = file.read()  # 读入一个中文txt文件,gbk -> utf-8
words = jieba.lcut(text)  # 使用jieba库分词,生成字符串
string = ' '.join(words)  # 使用join()方法,将分词生成的字符串以空格进行分割,生成词云时,字符串之间需要为空格
print(len(string))  # 输出词量

img = Image.open(current_path+'/source/super_sayaren.png')  # 打开图片
img_array = np.array(img)  # 将图片装换为数组

# 设置停止词
stopwords = set()
content = [line.strip() for line in open(
    current_path+'/source/stopwords.txt', 'r').readlines()]
stopwords.update(content)
stopwords.add("不行")

# 配置词云的背景,图片,字体大小等参数
wc = WordCloud(
    background_color= (0,0,0,0),  # 设置显示内容在什么颜色内
    width=1000,  # 设置图片宽,默认为400
    height=500,  # 设置图片高,默认为200
    mask=img_array,  # 设置词云背景模板
    font_path=font_path,  # 设置字体路径
    stopwords=stopwords,  # 设置需要屏蔽的词,如果为空,则使用内置的STOPWORDS
    scale=1.0,  # 图照比例进行放大画布,如设置为1.5,则长和宽都是原来画布的1.5倍
    max_words=1000,  # max_words图片上显示的最大词语的个数
    max_font_size=65,  # max_font_size为最大字体的大小
    min_font_size=4,  # min_font_size为最小字体大小,默认为4
    mode='RGBA',  # ,默认值RGB,当参数为“RGBA”并且background_color不为空时,背景为透明
    relative_scaling=1,  # 词频和字体大小的关联性,默认值
    collocations=True  # 是否包括两个词的搭配
)

wc.generate_from_text(string)  # 根据文本生成词云

image_colors = ImageColorGenerator(img_array)  # 获取color
# 按照给定的图片颜色布局生成字体颜色,当wordcloud尺寸比image大时,返回默认的颜色
plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")

plt.axis('off')  # 关闭坐标轴
plt.show()  # 显示图片
wc.to_file(current_path+'/source/word_cloud_super_sayaren.png')  # 保存图片

运行 Python 脚本

在图片文本的目录下,使用终端工具运行 python 脚本

./user_wordcloud.py

结果如下
对于词云图的结果如图

参考文档

  • 2
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值