总体思路如下:
1.读取PDF文件,将其中的英文单词提取出来
2.获得每个英文单词的词频,通过字典将英文单词及其词频配对
3.将英文单词按照词频由大到小排序
4.创建并写入docx文档
首先打开PDF文件用到了pdfplumber第三方库,具体应用如此下:
with pdfplumber.open(pdf_path) as pdf_file:
content = ''
for i in range(len(pdf_file.pages)):
# print("当前第 %s 页" % i)
page_text = pdf_file.pages[i]
page_content = page_text.extract_text()
if page_content:
content = content + page_content
# print(page_content)
将文本提取出来后,就需要从文本中提取出来每个独立的单词,这里用的是findall方法,用正则表达式:(其中string为原文本字符串)
str_list = re.findall(r'[A-Za-z]+', string)
进而收集词频:(提前需要新建一个字典)
for i in str_list:
if (i in dict.keys()):
dict[str(i)] += 1
else:
dict[str(i)] = 0
dict[str(i)] += 1
将字典按词频排序,下面语句将字典转换为了列表,当然是排序好的,reverse=False(默认)时为从小到大排序。所以需要再加一句将列表转换为字典再返回字典(如果需要的话)
dic_list = sorted(dict.items(), key=lambda x: x[1], reverse=True)[:n]
我这里还是转换为字典了,最后把字典的键值对写入文档中,用到了docx库。如下:
doc = docx.Document()
doc.add_paragraph('前二十个高频词及其词频为:')
for key, value in dict.items():
doc.add_paragraph("{} : {}".format(key, value))
doc.save('result.docx')
将以上结合起来:
(本来想用PyPDF2做一个后台观测进程的,但对结果没影响,就注销掉了,)
# coding:utf-8
"""
程序功能:
读取pdf中的文本,将其关键词输出至result。docx文档中。
"""
import re
import docx
# import PyPDF2
import pdfplumber
'''传入pdf文件地址,读取pdf文本,返回读出的文本字符串'''
def extract_content(pdf_path):
with pdfplumber.open(pdf_path) as pdf_file:
# pdf_image_reader = PyPDF2.PdfFileReader(open(pdf_path, 'rb'))
# pdf_image_reader.getNumPages()为页数
# print(pdf_image_reader.getNumPages())
content = ''
for i in range(len(pdf_file.pages)):
# print("当前第 %s 页" % i)
page_text = pdf_file.pages[i]
page_content = page_text.extract_text()
if page_content:
content = content + page_content
# print(page_content)
return content
'''将字符串中的单词按词频存入字典中并按词频由高到低排序,返回新的字典'''
def high_frequency_word(string, dict, n):
# 将没有意义的单词替换为空
'''
一开始用这个方法,发现把有些单词里的字母一起删掉了,所以在这里不替换,而是选择在字典那里操作
p = re.compile('(the|and|is|a|if|but|am|are|of|to|in|on|for|The)')
str_list = p.sub('', string)
'''
# 选出单词
str_list = re.findall(r'[A-Za-z]+', string)
# print(str_list)
for i in str_list:
if (i in dict.keys()):
dict[str(i)] += 1
else:
dict[str(i)] = 0
dict[str(i)] += 1
## 将没有意义的单词的键值对删除
wait_del = ['the', 'and', 'a', 'but', 'is', 'to', 'in', 'are', 'The', 'am', 'of', 'for', 'on', 'with', 'by', 'as',
'from', 'we']
for i in wait_del:
if (i in dict.keys()):
del dict[i]
# 按词频排序
# print(dict)
dic_list = sorted(dict.items(), key=lambda x: x[1], reverse=True)[:n]
# print(dic_list)
dict = {}
for key, value in dic_list:
dict[key] = value
# for i in dict.keys():
# print(i, dict[i])
return dict
# 调试部分
content = extract_content('Incremental Generative Occlusion Adversarial Suppression Network for Person ReID.pdf')
dict = {}
dict = high_frequency_word(content, dict, 20)
print(dict)
# 存入result.docx中
doc = docx.Document()
doc.add_paragraph('前二十个高频词及其词频为:')
for key, value in dict.items():
doc.add_paragraph("{} : {}".format(key, value))
doc.save('result.docx')
只支持英文,,,