由于建模需要,博主简单学习了词频分析和词云生成,本博客仅适用于初学者第一次使用来借鉴

Python实现词频分析和词云生成

1. 词频分析

词频分析:所谓词频分析就是对一篇文章中的高频词语进行列举并计数

实现方式:调用nltk的库,对.txt文本进行操作

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
import nltk
from nltk.tokenize import word_tokenize
import os
import re

stop_words = nltk.corpus.stopwords.words('english')
#stop_words调用nltk预先定义好的不需要统计的词语字典
newStopWords = ['I','It','The','one','use','this','They','Im','If','So','But','A','us','My',\
'This','We','These','You','For','She','He','Yet','As']
#newStopWords定义不需要筛选的词语
stop_words.extend(newStopWords)
#将不需要统计的词语添加到nltk的stopwords字典中
list = os.listdir('C:/Users/25496/Desktop/建模/原文')
#list声明需要进行词频统计的文章的存储路径(本脚本会将该路径下所有的文档进行词频统计)
print(list)
for content in list:
with open('C:/Users/25496/Desktop/建模/原文/'+content, encoding="utf-8") as f:
# 读取文件中的字符串
txt = f.read()
# 去除字符串中的标点、数字等
txt = re.sub('[,\.()":;!@#$%^&*\d]|\'s|\'', '', txt)
# 替换换行符,大小写转换,拆分成单词列表
word_list = txt.replace('\n', ' ').replace(' ', ' ').lower().split(' ')
word_tokens = word_tokenize(txt)
filtered_sentence = []
for w in word_tokens:
if w not in stop_words:
filtered_sentence.append(w)
word_count_dict = {}

for word in filtered_sentence:
# 统计字典中的词频
if word in word_count_dict.keys():
word_count_dict[word] += 1
else:
word_count_dict[word] = 1
# 按照单词出现次数排序
word_count_dict = sorted(word_count_dict.items(), key=lambda x: x[1], reverse=True)
# 输出到文件(如果是多个文件会输出到同一目录下)
with open("C:/Users/25496/Desktop/建模/结果/result_"+content, 'w', encoding="utf-8")as f1:
for i in word_count_dict:
f1.write("%s\t%s\n" % (i[0], str(i[1])))

容易出现的问题:

导nltk的数据包报错

在安装nltk的包之后我们还需要去安装nltk的数据包,至于缺少的数据包,这里作者建议各位在调试上述程序运行时的报错信息来确认缺少的数据包,下载时可以在python控制台输入如下指令

1
2
3
4
#第一种:图形用户界面,这种方式会生成一个图形用户界面,用户根据自己的需求来下载需要的数据包
nltk.download()
#第二种:命令行下载
nltk.download('【包名】')

常有报错:

(本机积极拒绝等。。。)这种问题出现的原因作者也出现了,多试几次之后莫名其妙就成功了。

2.词云生成

词云:如各位所见就是由多个词汇组合而成的一种图片,适合在各种场合使用

实现方式:调用wordcloud库(这个库好像需要matlab的库作为依赖)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from wordcloud import WordCloud
import PIL.Image as image
import numpy as np
import os
import matplotlib.pyplot as plt

#list定义了需要做词频分析的文件的存储路径
list = os.listdir('C:/Users/25496/Desktop/建模/原文')
#mask定义了一个图形蒙版
mask = np.array(image.open("C:/Users/25496/Desktop/建模/模板/timg.jpg"))

for content in list:
with open('C:/Users/25496/Desktop/建模/原文/' + content,encoding='utf-8') as fp:
text = fp.read()
# print(text)
#生成词云
wordcloud = WordCloud(background_color="white",mask=mask).generate(text)
wordcloud.to_file("C:/Users/25496/Desktop/建模/词云/img_"+content+".png")

WordCloud()方法内置的一些属性:

该方法可用来定义词云的基本属性

参数 描述
width 指定词云对象生成图片的宽度,默认400像素
height 指定词云对象生成图片的高度,默认200像素
min_font_size 指定词云中字体的最小字号,默认4号
max_font_size 指定词云中字体的最大字号,根据高度自动调节
font_step 指定词云中字体字号的步进间隔,默认为1
font_path 指定字体文件的路径,默认None
max_words 指定词云显示的最大单词数量,默认200
stop_words 指定词云的排除词列表,即不显示的单词列表
mask 指定词云形状,默认为长方形,需要指定mask
background_color 指定词云图片的背景颜色,默认为黑色

mask要求:作为蒙版,需要是白底的图片,词云将会以图片深色部分作为轮廓生成