一、揭开词云的神秘面纱
词云(WordCloud)也称为标签云或文字云,是文本数据可视化的艺术呈现方式,通过字体大小的差异展现关键词权重。
其核心价值体现在:
- 视觉降噪:过滤低频词汇,突出核心信息(如电商评论中高频出现的"物流快"、"质量好")
- 智能洞察:快速识别文本主题(新闻舆情分析中"人工智能"、"碳中和"等热词聚类)
- 跨域应用:适用于用户画像、政策分析、教育研究等场景
二、云词的实现方法
1、词云的实现方法
(1)在线的词云的制作
易词云 - 词云生成器https://www.yciyun.com/
(2)使用Python制作词云
pip install jieba
pip install WordCloud
# 基础三件套
pip install wordcloud matplotlib pillow
# 中文处理增强包
pip install jieba imageio
推荐使用清华镜像源加速下载:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple package_name
核心参数详解:
from wordcloud import WordCloud
wc = WordCloud(
width=1600, # 画布宽度(像素)
height=900, # 画布高度
background_color='#FFFFFF', # 背景色(支持HEX/RGB)
font_path='msyh.ttc', # 微软雅黑字体解决中文乱码
max_words=300, # 最大显示词数
collocations=False, # 禁用词组搭配(避免"北京"与"市"重复统计)
mask=mask_array, # 形状模板(需numpy数组)
contour_width=3, # 轮廓线宽
colormap='viridis' # 配色方案(spring/summer/autumn等)
)
三、入门到实践
例1 制作英文词云
from wordcloud import WordCloud # 导入WordCloud库
import matplotlib.pyplot as plt # 导入matplotlib库,用于显示图形
with open(r"C:\Users\HP\Desktop\笔记.txt",'r') as f: # 将笔记.txt文本中的数据导入程序
mytext = f.read() # 读取文本中的数据
wordcloud = WordCloud().generate(mytext) # 利用mytext中存储的文本内容来制作词云
plt.imshow(wordcloud,interpolation="bilinear") # 设置显示的词云图中无坐标轴
plt.axis("off")
plt.show() # 可视化显示
运行结果:
txt的内容如下
Youth is not a time of life; it is a state of mind; it is not a matter of rosy cheeks, red lips and supple knees; it is a matter of the will, a quality of the imagination, a vigor of the emotions; it is the freshness of the deep springs of life.Youth means a temperamental predominance of courage over timidity, of the appetite for adventure over the love of ease. This often exists in a man of 60 more than a boy of 20. Nobody grows old merely by a number of years.
例2 制作中文词云
from wordcloud import WordCloud # 导入WordCloud库
import matplotlib.pyplot as plt # 导入matplotlib库,用于显示图形
import jieba # 导入jieba库
with open(r"C:\Users\HP\Desktop\笔记.txt",'r',encoding='utf-8') as f: # 将笔记.txt文本中的数据导入程序,设置输入中文字符
text = f.read() # 读取文本中的数据
cut_text = " ".join(jieba.cut(text)) # 使用全模式进行中文分词
cloud = WordCloud(
# 设置字体,不指定就会出现乱码
font_path="C:\\Windows\\Fonts\\stxingka.ttf",
# font_path = path.join(d,'simsun.ttc'),
# 设置背景颜色
background_color = 'white',
# 词云形状
max_words = 4000,
# 最大号字体
max_font_size = 60
)
wCloud = cloud.generate(cut_text)
wCloud.to_file(r"C:\Windows\Fonts\cloud.jpg")
plt.imshow(wCloud,interpolation="bilinear") # 设置显示的词云图中无坐标轴
plt.axis("off")
plt.show() # 可视化显示
运行结果:
txt的内容如下
青春不是年华,而是心境;青春不是桃面、丹唇、柔膝,而是深沉的意志、恢宏的想象、炽热的感情;青春是生命的深泉在涌流。青春气贯长虹,勇锐盖过怯弱,进取压倒苟安。如此锐气,二十后生有之,六旬男子则更多见。年华并非岁月的简单累积,而是心智的沉淀与升华。