前一段时间,有个诉求,想了解下后台,大量反馈数据,其中重点集中在哪些内容。鉴于手边并无现成工具,可以想到快捷的办法是,对数据进行统一汇总,然后分词,将占比较高的关键词汇,生成词云图,从而形成对内容有大致解,为后面分析分析奠定方向。本文就如何基于 python 对文本做分词、快速生成词云图,做下探讨性分享。

为何选 python

Python 是一种易于学习又功能强大的编程语言。它优雅的语法和动态类型,以及解释型语言的本质,使它成为多数平台上写脚本,以及快速开发应用的理想语言。此外,Python 具有丰富强大的功能库,可以直接加以引用,省却很多工作量。

大致思路

假如已经获得文本,只需进行以下步骤即可:

  1. 对指定文本,基于 jieba 进行分词,得到词汇列表;
  2. 对所得词汇列表进行计数,获得高频词汇列表(过滤排除、由高到低排序);
  3. 根据排序后的高频词汇列表,取前 N(100)条,拼接为字符串;
  4. 依据拼接后字符串,基于 wordcloud、image 功能库生成词云图;

具体实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# gen-wordcloud-img.py
import jieba
import wordcloud
import PIL.Image as image
import numpy as np
relative_path = './wordcloud/'
target_path = 'target.txt'
def get_jieba_words():
content_str = open(relative_path + target_path, 'r', encoding='utf-8').read()
return jieba.lcut(content_str)
def get_high_frequency_word(param_list):
exclude_words_list = ['我们', '你们', '可以']
counts_dict = {}
for word in param_list:
if len(word) == 1:
continue
else:
is_word_exist = False
for ex_word in exclude_words_list:
if ex_word in word:
is_word_exist = True
if not is_word_exist:
if not word.isdigit():
count = counts_dict.get(word, 0) + 1
counts_dict[word] = count
return sorted(counts_dict.items(), key=lambda x: x[1], reverse=True)
def get_cloud_words(param_list):
result_str = ''
for item in param_list[0:100]:
occur_count = item[1]
for _ in range(occur_count):
result_str = result_str + ' ' + item[0]
return result_str
def gen_and_save_wordcloud_img(param_str):
mask = np.array(image.open(relative_path + "style.jpg"))
wc = wordcloud.WordCloud(width=1430, height=646, background_color="rgba(255, 255, 255, 0)",
mode="RGBA", font_path=relative_path + 'MSYH.TTC', collocations=False, max_words=100, mask=mask)
# 调用词云对象的 generate 方法,将文本传入
wc.generate(param_str)
# 将生成的词云以图片文件格式,保存在当前目录
wc.to_file(relative_path + 'output-result.png')
jieba_words_list = get_jieba_words()
print('所获得 jieba 分词个数为:', len(jieba_words_list))
high_frequency_word_list = get_high_frequency_word(jieba_words_list)
print('所得高频分词前 100 分别是:', high_frequency_word_list[0:100])
cloud_words_str = get_cloud_words(high_frequency_word_list)
gen_and_save_wordcloud_img(cloud_words_str)
print('已成功生成「词云图」并保存在当前目录.')

以上,便是全部代码实现;倘若真正使用,请参考 play-with-python @wordcloud。这是因为在生成词云图,支持自定义背景图片、以及宽高、字体、背景色等;由此用到了指定的图片和字体。

如何使用

此代码片段基于 python3 运行,如果本机器 python 环境默认为 python3,则可以直接基于 pip、python 来运行命令。在个人本机上,一些 Web 开发工具仍依赖于 python2.6 ,也就未将 python3 修改默认环境。

安装依赖

1
pip3 install wordcloud jieba numpy

一键调用

1
2
3
python3 gen-wordcloud-img.py
# OR
python gen-wordcloud-img.py

具体效果

个人很喜欢王小波先生、路遥先生。对王小波的杂文《工作与人生》,以及路遥先生的《早晨从中午开始》,基于这段脚本做下处理,来看下具体效果。

王小波《工作与人生》前 100 高频词汇词云图:
工作与人生
路遥先生《早晨从中午开始》前 100 高频词汇词云图:
早晨从中午开始

2021,即将来临。稀里糊涂的、过了这波橘云诡的 2020,愿所有人,在新的纪元里,平安喜乐,如意吉祥

于 2020 年 12 月 31 日,深圳.福田。

原文首发于个人最新博客:基于 python 对文本做分词、生成词云图


『有则推荐』: 自 2017 年初,就有开始利用闲余时光,打磨个人最新作品——「倾城之链」 ,有意将其打造成优良开放型平台,旨在云集全球优秀网站,让您更为便捷地探索互联网中那更广阔的世界;在这里,您可以轻松发现学习分享更多有用有趣的事物。目前仍在不断迭代、优化中,如果您对此感兴趣,不妨先尝试一下: 「倾城之链」;亦十分欢迎提出您宝贵意见或建议(亦可通过微信扫,描如下小程序码进行体验)。

小程序码 - 倾城之链

您可能感兴趣的文章


静晴轩 ~ 晚晴幽草轩
个人微信公众号晚晴幽草轩;名字取自:“天意怜幽草,人间重晚晴”。
专注互联网开发(Web 大前端、快应用、小程序),以及分享优质网站、AI 应用、效率工具、心得感悟等内容。

文章目录
  1. 1. 为何选 python
  2. 2. 大致思路
  3. 3. 具体实现
  4. 4. 如何使用
    1. 4.1. 安装依赖
    2. 4.2. 一键调用
  5. 5. 具体效果
    1. 5.1. 您可能感兴趣的文章