前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >教你利用Python绘制酷炫的词云图。

教你利用Python绘制酷炫的词云图。

作者头像
张俊红
发布2023-03-21 08:57:39
7060
发布2023-03-21 08:57:39
举报
文章被收录于专栏:张俊红张俊红

1. 效果展示

词云图想必大家都见过,是一种形式新颖的查看文本中出现最多词汇的图。

我使用Python的第三方库stylecloud来分别生成了 2 张词云图,读者可以猜一猜以下词云图的出处来自于哪里。

词云图 1

词云图 2

2. 实现过程

2.1 导入库

代码语言:javascript
复制
import pandas as pd
import stylecloud
import jieba
from collections import Counter

2.2 导入文本

代码语言:javascript
复制
with open('./三体.txt',encoding='utf-8') as f:
    txt = f.read()
txt = txt.split()

2.3 去除停用词

代码语言:javascript
复制
def stopwordslist():
    stopwords = [line.strip() for line in open('./常见中文停用词表.txt', 'r', encoding='gbk').readlines()]
    stopwords.append(' ') # 自定义添加停用词
    return stopwords

def movestopwords(sentence):
    stopwords = stopwordslist()  # 加载停用词的路径
    santi_words =[x for x in sentence if len(x) >1 and x not in stopwords]
    return ' '.join(santi_words)

data_cut = jieba.lcut(str(txt))
word_list = movestopwords(data_cut)
# print(word_list.split(' '))

2.4 统计词频

代码语言:javascript
复制
mycount = {}
for word in word_list.split(' '):
    mycount[word] = mycount.get(word,0)+1
counts_df = pd.DataFrame(mycount.items(), columns=['label', 'counts'])
counts_df.sort_values(by='counts',inplace=True, ascending = False)
counts_df.to_csv('./词频统计.csv',encoding='utf-8')
print('输出词频统计 成功!!')
print(counts_df.iloc[:10]) # 输出词频前 10 的词汇

2.5 生成词云图

代码语言:javascript
复制
stylecloud.gen_stylecloud(
                            text=word_list,
                            palette='tableau.BlueRed_6',
                            icon_name='fas fa-apple-alt',
                            font_path='./田英章楷书3500字.ttf',
                            output_name='《三体》词云图.png',
                            # custom_stopwords=stopwords
                            )

3. API详解

3.1 stylecloud.gen_stylecloud() 参数详解

代码语言:javascript
复制
gen_stylecloud(text=None,  # 输入文本(不含词频数)
               file_path=None,   # 输入文本/CSV 的文件路径 (可以含词频数)
               size=512,  # stylecloud 的大小(长度和宽度)
               icon_name='fas fa-flag',  # stylecloud 形状的图标名称(如 fas fa-grin)。[default: fas fa-flag]
               palette='cartocolors.qualitative.Bold_5',  # 调色板(通过 palettable 实现)。[default: cartocolors.qualitative.Bold_6]
               colors=None, # 自定义十六进制的字体颜色
               background_color="white",  # 背景颜色
               max_font_size=200,  # stylecloud 中的最大字号
               max_words=2000,  # stylecloud 可包含的最大单词数
               stopwords=True,  # 布尔值,用于筛除常见禁用词
               custom_stopwords=STOPWORDS, # 去除停用词
               icon_dir='.temp',
               output_name='stylecloud.png',   # stylecloud 的输出文本名
               gradient=None,  # 梯度方向
               font_path=os.path.join(STATIC_PATH,'Staatliches-Regular.ttf'), # stylecloud 所用字体
               random_state=None,  # 控制单词和颜色的随机状态
               collocations=True,
               invert_mask=False,
               pro_icon_path=None,
               pro_css_path=None)

3.2 palette (调色板)

❝参考网站:「https://jiffyclub.github.io/palettable/」

3.3 icon_name (图标名称)

❝参考网站:「https://fa5.dashgame.com/#/%E5%9B%BE%E6%A0%87」

4. 遗留的小问题

  • 中文博大精深,jieba对中文切词的准确性问题,可通过自定义添加词汇解决。
  • 重复无意义的词汇反复、连续出现,可通过机械压缩词汇的方法解决。

5. 资料下载

我已将以上配套数据文件和代码文件打包上传至我的 Github 和 Gitee,感兴趣的读者可以下载学习和练手。

  • 「Github 项目地址」

「https://github.com/don2vito/wechat_project/tree/master/词云」

  • 「Gitee 项目地址」

「https://gitee.com/don2vito/wechat_official_account/blob/master/038_词云」

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-07-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 俊红的数据分析之路 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 效果展示
  • 2. 实现过程
    • 2.1 导入库
      • 2.2 导入文本
        • 2.3 去除停用词
          • 2.4 统计词频
            • 2.5 生成词云图
            • 3. API详解
              • 3.1 stylecloud.gen_stylecloud() 参数详解
                • 3.2 palette (调色板)
                  • 3.3 icon_name (图标名称)
                  • 4. 遗留的小问题
                  • 5. 资料下载
                  领券
                  问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档