做淘宝客要建网站吗,影视网站怎么做,元气森林网络营销案例,网站正在建设中页面下载作者使用的是Python3.6版本。pdfminer在Python2和Python3中的安装和使用有一定的区别#xff0c;本文以Python为例。首先安装pdfminerpip install pdfminer3k官网对PDFMiner的介绍如下#xff1a;PDFMiner is a tool for extracting information from PDF documents. Unlike …作者使用的是Python3.6版本。pdfminer在Python2和Python3中的安装和使用有一定的区别本文以Python为例。首先安装pdfminerpip install pdfminer3k官网对PDFMiner的介绍如下PDFMiner is a tool for extracting information from PDF documents. Unlike other PDF-related tools, it focuses entirely on getting and analyzing text data. PDFMiner allows to obtain the exact location of texts in a page, as well as other information such as fonts or lines. It includes a PDF converter that can transform PDF files into other text formats (such as HTML). It has an extensible PDF parser that can be used for other purposes instead of text analysis.PDF的格式不是规范的很多情况下没有逻辑结构不能自适应页面大小的调整。PDFMiner是通过尝试猜测PDF的布局来重建其结构有时候效果并不理想。import importlib
import sys
import timeimportlib.reload(sys)
time1 time.time()import os.path
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 PDFTextExtractionNotAlloweddef parse(pdf_path,txt_path):解析PDF文本并保存到TXT文件中fp open(text_path,rb)# pdf1 urlopen(http://www.tencent.com/20160321.pdf)#用文件对象创建一个PDF文档分析器parser PDFParser(fp)#创建一个PDF文档doc PDFDocument()#连接分析器与文档对象parser.set_document(doc)doc.set_parser(parser)#提供初始化密码如果没有密码就创建一个空的字符串doc.initialize()#检测文档是否提供txt转换不提供就忽略if not doc.is_extractable:raise PDFTextExtractionNotAllowedelse:#创建PDF资源管理器来共享资源rsrcmgr PDFResourceManager()#创建一个PDF设备对象laparams LAParams()device PDFPageAggregator(rsrcmgr,laparamslaparams)#创建一个PDF解释其对象interpreter PDFPageInterpreter(rsrcmgr,device)#循环遍历列表每次处理一个page内容# doc.get_pages() 获取page列表for page in doc.get_pages():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(txt_path,a) as f:results x.get_text()print(results)f.write(results n)if __name__ __main__:pdf_path ./test.pdftxt_path ./test.txtparse(pdf_path,txt_path)time2 time.time()print(总共消耗时间为:,time2-time1)上述代码只能解析正常的PDF内容在实际应用场景中很多PDF文档可能是加密的如何处理解密的PDF文件也是我们需要get的技能。pydf2这个库能够实现对PDF文件进行加密和解密。