NLP笔记 - Word Tokenization // wordcloud 词云图教程

面向对象:想做简单的文本可视化分析 选手。

概念解释

  • 词云图(wordcloud):是这两年比较火的文本可视化分析的一种,上图就知道说的啥了:
  • jieba:python库,用于中文分词。

  • wordcloud:python库,用于词云图制作。

  • 停用词表(stopwords):在英文中像“the / of / a / for /…”,在中文中像“的 / 是 / 也 / 之 /…”这样的没有实际意义却出现频率较高的词。为了防止这些词抢了比如故事主角名的位置,就事先作为停用词,不进入文本分析。

按规矩,先上文档结构图!文档中所需文件的下载地址,点这里

1
2
3
4
5
6
7
8
9
10
11
12
|-wordcloud //新建文件夹
|- data //新建文件夹
|- alice.txt //下载文件
|- yxgltext.txt //下载文件
|- stopwords.txt //下载文件
|- SourceHanSerifK-Light.otf //下载文件
|- plot //新建文件夹
|- alice_color.png //下载图片
|- queen.jpg //下载图片
|- alice1.py //新建python文件
|- alice2.py //新建python文件
|- queen.py //新建python文件

英文词云图

例子1:10行代码搞定的词云图 // alice1.py

输入:

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
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 3 17:53:03 2018

@author: Yi
"""

import os
os.chdir("C:/Users/Yi/Desktop/nlp/wordcloud") # 换成你的wordcloud文件夹所在路径
from wordcloud import WordCloud

f = open('data/alice.txt').read()
wordcloud = WordCloud(background_color="white",width=1000, height=860, margin=2).generate(f)
# width,height,margin可以设置图片属性
# generate 可以对全部文本进行自动分词,但是对中文支持不好
# wordcloud = WordCloud(font_path = r'D:\Fonts\simkai.ttf').generate(f)
# 你可以通过font_path参数来设置字体集
# background_color参数为设置背景颜色,默认颜色为黑色

import matplotlib.pyplot as plt
ax = plt.imshow(wordcloud)
fig = ax.figure
fig.set_size_inches(25,20) # 可调节图片紧密 尺寸程度
plt.axis("off")
plt.show()

wordcloud.to_file('plot/test.png')

输出:

例子2:有形状的词云图 // alice2.py

输入:

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 4 10:05:29 2018

@author: Yi
"""

import os
os.chdir("C:/Users/Yi/Desktop/nlp/wordcloud")

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator

# Read the whole text.
text = open('data/alice.txt').read()
alice_coloring = np.array(Image.open("plot/alice_color.png")) # 可随意更换图片
stopwords = set(STOPWORDS)
stopwords.add("said")

# 你可以通过 mask 参数 来设置词云形状
wc = WordCloud(background_color="white", max_words=2000, mask=alice_coloring,
stopwords=stopwords, max_font_size=40, random_state=42)
# generate word cloud
wc.generate(text)

# create coloring from image
image_colors = ImageColorGenerator(alice_coloring)


# 方式 1 -------------------------------------------------------------------
# show

#fig, axes = plt.subplots(1, 3)
#axes[0].imshow(wc, interpolation="bilinear")
#axes[1].imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")
#axes[2].imshow(alice_coloring, cmap=plt.cm.gray, interpolation="bilinear")
#
#for ax in axes:
# ax.set_axis_off()
# fig = ax.figure
# fig.set_size_inches(25,20) # 可调节图片紧密 尺寸程度
#plt.show()


# 方式 2 -------------------------------------------------------------------
# show
# 在只设置mask的情况下,你将会得到一个拥有图片形状的词云
plt.axis("off")
ax = plt.imshow(wc, interpolation="bilinear")
fig = ax.figure
fig.set_size_inches(25,20) # 可调节图片紧密 尺寸程度
plt.figure()
# recolor wordcloud and show
# we could also give color_func=image_colors directly in the constructor
# 我们还可以直接在构造函数中直接给颜色
# 通过这种方式词云将会按照给定的图片颜色布局生成字体颜色策略
plt.axis("off")
ax = plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")
fig = ax.figure
fig.set_size_inches(25,20) # 可调节图片紧密 尺寸程度
plt.figure()


plt.axis("off")
ax = plt.imshow(alice_coloring, cmap=plt.cm.gray, interpolation="bilinear")
fig = ax.figure
fig.set_size_inches(25,20) # 可调节图片紧密 尺寸程度
plt.show()

输出:


中文词云图

例子:延禧攻略的白月光 // queen.py

中文与英文还是有点不一样的,在停用词表就需要自己弄一套等等。记得跑之前要把该下载的文件下载到文件夹里。

输入:

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
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 3 18:27:38 2018

@author: Yi
"""

import os
os.chdir("C:/Users/Yi/Desktop/nlp/wordcloud")

import jieba.analyse # 导入结巴分词
import numpy as np # numpy
from wordcloud import WordCloud, STOPWORDS # 词云工具和自带的的停用词,英文
from PIL import Image # 图片处理
import matplotlib.pyplot as plt

def handle(textfile, stopword):
with open(textfile, 'r') as f:
data = f.read()

wordlist = jieba.analyse.extract_tags(data, topK=100) # 分词,取前100
wordStr = " ".join(wordlist)
print (wordStr)

hand = np.array(Image.open('plot/queen.jpg')) # 打开一张图片,词语以图片形状为背景分布

my_cloudword = WordCloud(
# wordcloud参数配置
width=1024,
height=768,
background_color = 'white', # 背景颜色设置白色
mask = hand, # 背景图片
max_words = 100, # 最大显示的字数
stopwords = stopword, # 停用词
max_font_size = 100, # 字体最大值
font_path='data/SourceHanSerifK-Light.otf', # 设置中文字体,若是有中文的话,这句代码必须添加,不然会出现方框,不出现汉字
random_state=3, # 设置有多少种随机生成状态,即有多少种配色方案
)

my_cloudword.generate(wordStr) # 生成图片
my_cloudword.to_file('plot/queen.png') # 保存

plt.axis('off') # 是否显示x轴、y轴下标
ax = plt.imshow(my_cloudword) # 显示词云图
fig = ax.figure
fig.set_size_inches(25,20) # 可调节图片紧密 尺寸程度
plt.show() # 显示


stopwords = open('data/stopwords.txt').read()
stopwords = set(stopwords.split('\n'))

if __name__ == '__main__':
handle('data/yxgl.txt', stopwords)

输出:

再来一次:

白月光皇后的人头形状和扇子形状都还在的。

写在最后

这里用到的文本分析的技术只停留在分词阶段,还是比较简单的。可视化分析永远是最吸引人的。快去试一下吧~😋

打赏2块钱,帮我买杯咖啡,继续创作,谢谢大家!☕~
0%