← 返回教程目录
第 3 章 · 第 1 节 词云

词云入门:5 行代码出图

Word Cloud 101: 5 Lines to a Chart

wordcloud 是 Python 最经典的词云库,5 行代码出图,论文 / 报告 / PPT 直接用。

1. 安装

pip install wordcloud jieba matplotlib

2. 最简版:英文词云

from wordcloud import WordCloud


import matplotlib.pyplot as plt





text = "python is great python is powerful python text analysis"





wc = WordCloud(width=800, height=400, background_color='white').generate(text)


plt.imshow(wc, interpolation='bilinear')


plt.axis('off')


plt.savefig('wordcloud_en.png', dpi=150, bbox_inches='tight')

3. 中文词云(必须先分词)

import jieba


from wordcloud import WordCloud





text = '这款手机真不错,拍照很清晰。物流太慢了,屏幕有点黄。'





# 关键:用空格连接分词结果(英文词云默认按空格切)


words = ' '.join(jieba.lcut(text))





wc = WordCloud(


    width=800, height=400,


    font_path='/System/Library/Fonts/PingFang.ttc',  # Mac 中文


    background_color='white',


).generate(words)


wc.to_file('wordcloud_zh.png')
font_path 必填!不填中文全是方块。Windows 用 msyh.ttc,Mac 用 PingFang.ttcSTHeiti Medium.ttc,Linux 用 wqy-zenhei.ttc

4. 从文件读 5 万条评论出词云

import pandas as pd


import jieba


from wordcloud import WordCloud





df = pd.read_csv('comments_50k.csv')





# 全部评论拼起来,去停用词


stopwords = set(['的', '了', '是', '我', '你', '他', '也', '就'])


all_words = []


for text in df['text']:


    for w in jieba.lcut(str(text)):


        if w not in stopwords and len(w) > 1:


            all_words.append(w)





text_for_wc = ' '.join(all_words)





wc = WordCloud(


    width=1200, height=600,


    font_path='/System/Library/Fonts/PingFang.ttc',


    background_color='white',


    max_words=200,        # 最多显示 200 个词


    colormap='viridis',  # 配色


).generate(text_for_wc)





wc.to_file('wordcloud_50k.png')

5. 调参 6 件套

WordCloud(


    width=1200, height=600,        # 画布大小


    background_color='white',     # 背景色(白/黑/透明)


    max_words=200,                 # 最多显示词数


    max_font_size=120,             # 最大字号


    min_font_size=8,               # 最小字号(过滤低频词)


    colormap='viridis',           # 配色方案(支持 matplotlib 全部)


    font_path=...,                 # 中文字体路径


    mask=...,                      # 自定义形状(下节讲)


)

下节我们让词云变成任意形状 — 用图片当 mask。

嫌 matplotlib 出图丑?我们词云软件支持自定义形状 + 等大文字

配套软件内置案例数据 + 模板,导入即出图,无需写代码

查看淘宝软件 →