简介

“词云”是通过形成“关键词云层”或“关键词渲染”,对网络文本中出现频率较高的“关键词”的视觉上的突出。过滤掉大量的文本信息,使浏览网页者只要一眼扫过文本就可以领略文本的主旨。

准备工作

需要安装的库(根据提示缺啥补啥吧)

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  # 科学计算

path_txt = 'D:/pythonProject'  # 文本路径
path_bg = 'D:/pythonProject'  # 词云背景模板路径
font_path = 'C:/Windows/Fonts/SIMYOU.TTF'  # 设置字体,可以显示中文

file = open('D:/pythonProject/job.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('cat.png')  # 打开图片
img_array = np.array(img)  # 将图片装换为数组

# 设置停止词 
stopwords = set()
content = [line.strip() for line in open('stopwords.txt', 'r').readlines()]
stopwords.update(content)

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

wc.generate_from_text(string)  # 根据文本生成词云
image_colors = ImageColorGenerator(img_array)  # 获取color
plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")  # 按照给定的图片颜色布局生成字体颜色,当wordcloud尺寸比image大时,返回默认的颜色
plt.axis('off')  # 关闭坐标轴
plt.show()  # 显示图片
wc.to_file('D:/pythonProject/word_cloud_cat.png')  # 保存图片

运行效果

背景图
cat.png
生成的词云图
wordcloud_cat.png

生成背景图片

图片的背景最好为白色
背景图片的路径:
完整路径:如D:/pythonProject/cat.png
若图片与Python代码在同一个文件夹,直接写图片名称+后缀,例如cat.png
1.使用 matplotlib库读取图片

img = plt.imread("cat.png")

2.使用numpy库和PIL库,PIL库用于打开图片,numpy库用于将图片转化为数组

img = Image.open('cat.png')  # 打开图片
img_array = np.array(img)  # 将图片装换为数组

设置停止词

可以从网上下载txt文件后再根据要处理的数据进行修改

# stopwords = "的是在有着还和它也要,./;'[]~!@#$%^&*()_+,。、;‘ 【】~!@#¥%……&*()——+《 》?:“{}<>?:\n\r"   
stopwords = set()
content = [line.strip() for line in open('stopwords.txt', 'r').readlines()]
stopwords.update(content)

若不想出现"圣诞"这个词,可以用add方法添加

stopwords.add('圣诞')

重新运行后效果
在这里插入图片描述

可以发现词汇“圣诞”已经被停用,不再显示

按照背景图片颜色生成字体颜色

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

用上述代码运行出的图片与背景图的颜色保持一致
如果将上述代码改为

plt.imshow(wc)

则运行后效果为
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐