1

如何用Python 制作词云-对1000首古诗做词云分析

 2 years ago
source link: https://codeshellme.github.io/2020/12/ml-wordcloud/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

如何用Python 制作词云-对1000首古诗做词云分析

2020-12-12

1559 字 阅读约需 4 分钟

公号:码农充电站pro

主页:https://codeshellme.github.io

今天来介绍一下如何使用 Python 制作词云

词云又叫文字云,它可以统计文本中频率较高的词,并将这些词可视化,让我们可以直观的了解文本中的重点词汇。

词的频率越高,词显示的大小也就越大。

1,wordcloud 模块

wordcloud 是一个词云生成器,它不仅是一个 Python 库,还是一个命令行工具。我们可以通过 wordcloud 官方文档,和示例库来学习如何使用它。

在使用 wordcloud 之前,需要先安装它:

pip install wordcloud

2,WordCloud 类

WordCloud 类用于创建词云对象,先来看下它的原型:

WordCloud(font_path=None,
width=400, height=200,
margin=2, ranks_only=None,
prefer_horizontal=0.9,
mask=None, scale=1,
color_func=None, max_words=200,
min_font_size=4, stopwords=None,
random_state=None,
background_color='black',
max_font_size=None,
font_step=1, mode='RGB',
relative_scaling='auto',
regexp=None, collocations=True,
colormap=None, normalize_plurals=True,
contour_width=0, contour_color='black',
repeat=False, include_numbers=False,
min_word_length=0,
collocation_threshold=30)

可以看到,WordCloud 类有很多参数可以设置,这里介绍一些常用的参数:

  • font_path:设置字体文件路径,字体文件以 .ttf 为后缀。
    • 如果分析的文本是中文,则需要设置中文字体,否则会乱码。
  • background_color:设置图片背景颜色,默认为 black,也可以设置为 white 等。
  • mask:设置背景图片。
  • max_words:设置最大的词数,默认为200。
  • stopwords:设置停用词。
  • max_font_size:设置字体最大值。
  • width:设置画布的宽度,默认为400。
  • height:设置画布的高度,默认为200。
  • random_state:设置多少种随机状态,即多少种颜色。

在创建好词云对象后,可以使用 generate 方法生成词云,并使用 to_file 方法将词云图像保存在文件中。

generate 方法的原型如下:

generate(text)

参数text 是一个用空格隔开的文本字符串。如果分析的是中文,需要先用 jieba 进行分词,可以参考这里

除了将词云图像保存在文件中,还可以使用 Matplotlib 模块显示词云图像,示例代码如下:

import matplotlib.pyplot as plt
plt.imshow(wordcloud) # wordcloud 是词云对象
plt.axis("off") # 用于关闭坐标轴
plt.show()

3,一个简单的示例

下面演示一个最简单的示例,来看如何使用 wordcloud

首先创建词云对象

from wordcloud import WordCloud
wc = WordCloud()

生成词云:

text = "Python is a programming language, it is easy to use."
wc.generate(text)

词云对象的 words_ 属性中存储了每个单词的(归一化后的)权重,权重的范围是 (0, 1]

words_ 属性是一个字典类型,它存储的键的最大个数为 max_words,即 WordCloud 类的参数。

>>> wc.words_
{'Python': 1.0, 'programming': 1.0, 'language': 1.0, 'easy': 1.0, 'use': 1.0}
# 示例中的这些单词出现的频率都相等(均为 1),
# 所以它们的权重都是 1。

Matplotlib 展示词云图像:

import matplotlib.pyplot as plt
plt.imshow(wc)
plt.axis("off")
plt.show()

词云图像如下:

4,对古诗做词云分析

我在这里准备了一个案例,是对1000 首古诗做词云分析。

代码目录如下:

wordcloud/
├── SimHei.ttf
├── gushi.txt
└── gushi_wordcloud.py
  • SimHei.ttf:是一个字体文件,避免词云分析时出现中文乱码。
  • gushi.txt:该文件中包含了1000 首古诗
  • gushi_wordcloud.py:是词云分析代码

我将代码也放在这里,方便查看:

#!/usr/bin/env python
# coding=utf-8
import os
import sys
import jieba
from wordcloud import WordCloud
if sys.version.startswith('2.'):
reload(sys)
sys.setdefaultencoding('utf-8')
# 去掉一些作者的名字
STOPWORDS = [
u'李白', u'杜甫', u'辛弃疾', u'李清照', u'毛泽东', u'苏轼',
u'李商隐', u'王维', u'白居易', u'李煜', u'杜牧',
def load_file(file_path):
if sys.version.startswith('2.'):
with open(file_path) as f:
lines = f.readlines()
else:
with open(file_path, encoding='utf-8') as f:
lines = f.readlines()
content = ''
for line in lines:
line = line.encode('unicode-escape').decode('unicode-escape')
line = line.strip().rstrip('\n')
content += line
words = jieba.cut(content)
for w in words:
# 如果词的长度小于 2,则舍去
if len(w) < 2: continue
l.append(w)
return ' '.join(l)
if __name__ == '__main__':
file_path = './gushi.txt'
content = load_file(file_path)
wc = WordCloud(
font_path="./SimHei.ttf",
stopwords=STOPWORDS,
width=2000, height=1200)
wc.generate(content)
wc.to_file("wordcloud.jpg")
  • STOPWORDS 停用词列表,是一些作者的名字。
  • load_file 方法用于加载文本,其中用到了 jieba 分词。

最后将词云图像保存在了 wordcloud.jpg 文件中,如下:

我们也可以从词云对象的words_ 属性中查看每个词的权重,这里我列出前十个:

('明月', 1.0)
('今日', 0.9130434782608695)
('不知', 0.8405797101449275)
('何处', 0.8260869565217391)
('不见', 0.8115942028985508)
('春风', 0.7536231884057971)
('无人', 0.7536231884057971)
('不可', 0.7536231884057971)
('万里', 0.7536231884057971)
('现代', 0.6666666666666666)

(本节完。)


推荐阅读:

如何使用Python 进行数据可视化

Apriori 算法-如何进行关联规则挖掘

PageRank 算法-Google 如何给网页排名

K 均值算法-如何让数据自动分组

KNN 算法-实战篇-如何识别手写数字


欢迎关注作者公众号,获取更多技术干货。

文章作者 @码农加油站

上次更改 2020-12-12

AdaBoost 算法-分析波士顿房价数据集 EM 算法-对鸢尾花数据进行聚类

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK