PDFToTXT

1. 如何用python将PDF转为TXT
所需依赖:pdfminer3k、python-docx
所需步骤:解析PDF、取出数据、保存为TXT/Word
遇到的坑:

  1. 最开始安装的依赖为pdfminer,而python环境为3.7,导致无法调用(并且包的依赖其实应该是install pdfminer3k才对),这里我一直无法理解的就是明明包名为pdfminer,但是安装却要是pdfminer3k,其他类似的很多,表示暂时还无法理解,所以每次都需要相应的依赖是个啥……
  2. Document无法引用,安装的docx不存在,哈哈,这个是因为之前用VS2017安装的docx里面引用了exceptions,python3.x版本移除了exceptions模块,但是docx包中引用了该模块,故有掉进去了,嗯嗯,在https://www.lfd.uci.edu/~gohlke/pythonlibs/ 安装新的python_docx‑0.8.10‑py2.py3‑none‑any.whl即可。
  3. 上面引用没问题后,下面一个坑好像就么得了,然后去理解包中使用的方法的含义吧——“努力、奋斗”

方法解读:
“窃”一个图:
要解析PDF至少需要两个类:PDFParser 和 PDFDocument,PDFParser 从文件中提取数据,PDFDocument保存数据。另外还需要PDFPageInterpreter去处理页面内容,PDFDevice将其转换为我们所需要的。PDFResourceManager用于保存共享内容例如字体或图片。

Python os.listdir() 方法:

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os, sys

# 打开文件
path = "/var/www/html/"
dirs = os.listdir( path )

# 输出所有文件和文件夹
for file in dirs:
print file

2. Let’s do it

PDF转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
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env python
# encoding: utf-8

"""
@author: Ed
@software: VS2017
@file: PDFToTXT.py
@time: 2019/1/29
"""
import sys
import importlib
importlib.reload(sys)

from pdfminer.pdfparser import PDFParser,PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LTTextBoxHorizontal,LAParams
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed

'''
解析pdf文本,保存到txt文件中
'''

path = r'E:\pyworkspace\pdf2word-master\Test\pdf\Test PDF to Word.pdf'
def parse():
fp = open(path, 'rb') # 以二进制读模式打开

praser = PDFParser(fp) #用文件对象来创建一个pdf文档分析器,PDFParser 从文件中提取数据
doc = PDFDocument() #保存数据
praser.set_document(doc) # 连接分析器 与文档对象
doc.set_parser(praser)
doc.initialize() # 提供初始化密码,如果没有密码 就创建一个空的字符串

# 检测文档是否提供txt转换,不提供就忽略
if not doc.is_extractable:
raise PDFTextExtractionNotAllowed
else:
rsrcmgr = PDFResourceManager() # 创建PDf 资源管理器 来管理共享资源
laparams = LAParams()
device = PDFPageAggregator(rsrcmgr, laparams=laparams) # 创建一个PDF设备对象
interpreter = PDFPageInterpreter(rsrcmgr, device) # 创建一个PDF解释器对象,处理页面内容

# 循环遍历列表,每次处理一个page的内容
for page in doc.get_pages(): # doc.get_pages() 获取page列表
interpreter.process_page(page) # 接受该页面的LTPage对象
layout = device.get_result() # 这里layout是一个LTPage对象 里面存放着 这个page解析出的各种对象 一般包括LTTextBox, LTFigure, LTImage, LTTextBoxHorizontal 等等 想要获取文本就获得对象的text属性,

for x in layout:
if (isinstance(x, LTTextBoxHorizontal)):
with open(r'E:/pyworkspace/pdf2word-master/Test/1.txt', 'a') as f:
results = x.get_text()
print(results)
f.write(results + '\n')

if __name__ == '__main__':
parse()

PDF转Word

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
71
72
73
74
75
76
import os
from configparser import ConfigParser
from io import StringIO
from io import open
from concurrent.futures import ProcessPoolExecutor

from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import process_pdf
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from docx import Document


def read_from_pdf(file_path):
with open(file_path, 'rb') as file:
resource_manager = PDFResourceManager() # 创建PDf 资源管理器
return_str = StringIO()
lap_params = LAParams()

device = TextConverter(
resource_manager, return_str, laparams=lap_params) # 创建一个PDF设备对象
process_pdf(resource_manager, device, file)
device.close()

content = return_str.getvalue()
return_str.close()
return content


def save_text_to_word(content, file_path):
doc = Document()
for line in content.split('\n'):
paragraph = doc.add_paragraph()
paragraph.add_run(remove_control_characters(line))
doc.save(file_path)


def remove_control_characters(content):
mpa = dict.fromkeys(range(32))
return content.translate(mpa)


def pdf_to_word(pdf_file_path, word_file_path):
content = read_from_pdf(pdf_file_path)
save_text_to_word(content, word_file_path)


def main():
config_parser = ConfigParser()
config_parser.read('config.cfg')
config = config_parser['default']

tasks = []
with ProcessPoolExecutor(max_workers=int(config['max_worker'])) as executor:
for file in os.listdir(config['pdf_folder']):
extension_name = os.path.splitext(file)[1]
if extension_name != '.pdf':
continue
file_name = os.path.splitext(file)[0]
pdf_file = config['pdf_folder'] + '/' + file #E:\pyworkspace\pdf2word-master\Test\pdf
word_file = config['word_folder'] + '/' + file_name + '.docx' #E:\pyworkspace\pdf2word-master\Test\word
print('正在处理: ', file)
result = executor.submit(pdf_to_word, pdf_file, word_file)
tasks.append(result)
while True:
exit_flag = True
for task in tasks:
if not task.done():
exit_flag = False
if exit_flag:
print('完成')
break;


if __name__ == '__main__':
main()
Donate comment here
-------------本文结束感谢您的阅读-------------
Fork me on GitHub