本文實例為大家分享了python實現pdf轉word/txt,供大家參考,具體內容如下
依賴包:pdfminer3k
可以通過pip安裝;也可以到官網下載,解壓,進入文件夾,輸入命令setup.py install安裝軟件。
源代碼:
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
|
#!/usr/bin/python # -*- coding: utf-8 -*- 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 * from pdfminer.pdfinterp import PDFTextExtractionNotAllowed ''''' 解析pdf文件,獲取文件中包含的各種對象 ''' # 解析pdf文件函數 def parse(pdf_path): fp = open (pdf_path, 'rb' ) # 以二進制讀模式打開 # 用文件對象來創建一個pdf文檔分析器 parser = PDFParser(fp) # 創建一個PDF文檔 doc = PDFDocument() # 連接分析器 與文檔對象 parser.set_document(doc) doc.set_parser(parser) # 提供初始化密碼 # 如果沒有密碼 就創建一個空的字符串 doc.initialize() # 檢測文檔是否提供txt轉換,不提供就忽略 if not doc.is_extractable: raise PDFTextExtractionNotAllowed else : # 創建PDf 資源管理器 來管理共享資源 rsrcmgr = PDFResourceManager() # 創建一個PDF設備對象 laparams = LAParams() device = PDFPageAggregator(rsrcmgr, laparams = laparams) # 創建一個PDF解釋器對象 interpreter = PDFPageInterpreter(rsrcmgr, device) # 用來計數頁面,圖片,曲線,figure,水平文本框等對象的數量 num_page, num_image, num_curve, num_figure, num_TextBoxHorizontal = 0 , 0 , 0 , 0 , 0 # 循環遍歷列表,每次處理一個page的內容 for page in doc.get_pages(): # doc.get_pages() 獲取page列表 num_page + = 1 # 頁面增一 interpreter.process_page(page) # 接受該頁面的LTPage對象 layout = device.get_result() for x in layout: if isinstance (x,LTImage): # 圖片對象 num_image + = 1 if isinstance (x,LTCurve): # 曲線對象 num_curve + = 1 if isinstance (x,LTFigure): # figure對象 num_figure + = 1 if isinstance (x, LTTextBoxHorizontal): # 獲取文本內容 num_TextBoxHorizontal + = 1 # 水平文本框對象增一 # 保存文本內容 with open (r 'test.doc' , 'a' ,encoding = 'utf-8' ) as f: #生成doc文件的文件名及路徑 results = x.get_text() f.write(results) f.write( '\n' ) print ( '對象數量:\n' , '頁面數:%s\n' % num_page, '圖片數:%s\n' % num_image, '曲線數:%s\n' % num_curve, '水平文本框:%s\n' % num_TextBoxHorizontal) if __name__ = = '__main__' : pdf_path = r 'test.pdf' #pdf文件路徑及文件名 parse(pdf_path) |
此腳本只能將pdf文件轉換成純文本文件,沒有任何格式。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/Initiallysunny/article/details/79960838