Hallo,各位小伙伴大家好啊!这个专栏是用来分享数据处理以及数据可视化的一些常见操作,以及自己的一些学习笔记,希望能给大家带来帮助呀!感兴趣的小伙伴也欢迎私信或者评论区交流呀!
Python编程读取至少一篇pdf文档。并编程实现以下功能:
①实现其中的热词统计分析。
②绘制热词统计分析的词云
一、PDF文档的选择
我选择的PDF中文字内容如下:
编辑
二、效果展示
编辑
编辑
三、完整代码
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
| import pdfplumber import jieba from wordcloud import WordCloud import numpy as np import matplotlib.pyplot as plt plt.rcParams['font.sans-serif']=['SimHei'] plt.rcParams['axes.unicode_minus']=False
with pdfplumber.open('中华文化.pdf') as f: for page in f.pages: text = page.extract_text() txt_f = open(r'中华文化.txt', mode='a', encoding='utf-8') txt_f.write(text)
file = open('中华文化.txt',encoding='utf-8') file = file.read() txtlist = jieba.lcut(file) string = " ".join(txtlist) stop_words = {} counts = {} for txt in txtlist: if len(txt) == 1: stop_words[txt] = stop_words.get(txt, 0) + 1 else: counts[txt] = counts.get(txt, 0) + 1 items = list(counts.items()) items.sort(key=lambda x: x[1], reverse=True) y1 = [] labels = [] for i in range(1,10): y1.append(items[i][1]) labels.append(items[i][0])
width = 0.3 x = np.arange(len(y1)) a = [i for i in range(0,9)] plt.xticks(a,labels,rotation = 30) plt.bar(x=x,height=y1,width=width) plt.title('PDF文件中热词统计分析') plt.savefig("热词统计分析.png") plt.show() print("-------热词统计分析完成!-------") stoplist=[] item = list(stop_words.items()) for i in range(len(item)): txt,count = item[i] stoplist.append(txt)
setlist = set(stoplist) wcd = WordCloud(width=1000, height=700, background_color='white', font_path='msyh.ttc', scale=15, stopwords=setlist) wcd.generate(string) wcd.to_image() print("-------热词词云生成完成!-------") wcd.to_file('词云.png')
|
四、总结
题目要求读取至少一篇pdf文档,那么需要用到pdfplumber库,用with pdfplumber.open(‘中华文化.pdf’) as f:这条语句将文件打开,之后用for循环读取文件的每一页,并将读取到的内容存到txt文件中。
再利用jieba分词库对文本处理,使用精确模式对文本进行分词,列表转化为字符串,绘制词云要传入的对象是字符串.
接着统计词语及其出现的次数,通过键值对的形式存储要排除的词及出现次数,通过键值对的形式存储词语及其出现的次数,注意将当个词语删除,遍历所有词语,每出现一次其对应的值加 1,根据词语出现的次数进行从大到小排序。
根据上面的处理结果画热词统计分析图,用for循环向label和y1中添加排名前十的词汇和它对应出现的次数,用plt画出,横坐标为对应词汇,纵坐标为出现次数,可以看出,出现最多的词是“父母”和“我们”、其次是“弟子规”和“朋友”。
创建排除单个词的列表,遍历列表中所有的字典,将key添加到要排除的列表,将列表转化为集合,后面WordCloud()方法的stopwords传入的参数要求为集合,将string变量传入generate()方法,给词云输入文字,利用WordCloud生成词云照片。