1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Python提取PDF中的文字和图片

Python提取PDF中的文字和图片

时间:2021-08-16 19:32:54

相关推荐

Python提取PDF中的文字和图片

一,使用Python提取PDF中的文字

# 只能处理包含文本的PDF文件#coding=utf-8import sysimport importlibimportlib.reload(sys)from pdfminer.pdfparser import PDFParser,PDFDocumentfrom pdfminer.pdfinterp import PDFResourceManager,PDFPageInterpreterfrom pdfminer.converter import PDFPageAggregatorfrom pdfminer.layout import LTTextBoxHorizontal,LAParamsfrom pdfminer.pdfinterp import PDFTextExtractionNotAlloweddef ReadPDF(SourceFilePath,ToFilePath):# 以二进制形式打开PDF文件FileObj = open(SourceFilePath,"rb")# 创建一个PDF文档分析器Parser = PDFParser(FileObj)# 创建PDF文档PDFFile = PDFDocument()# 链接分析器与文档对象Parser.set_document(PDFFile)PDFFile.set_parser(Parser)# 提供初始化密码PDFFile.initialize()# 检测文档是否提供txt转换if not PDFFile.is_extractable:raise PDFTextExtractionNotAllowedelse:# 解析数据# 数据管理器Manager = PDFResourceManager()# 创建一个PDF设备对象Laparams = LAParams()device = PDFPageAggregator(Manager,laparams = Laparams)# 创建解释器对象Interpreter = PDFPageInterpreter(Manager,device)# 开始循环处理,每次处理一页for Page in PDFFile.get_pages():Interpreter.process_page(Page)Layout = device.get_result()for x in Layout:if (isinstance(x,LTTextBoxHorizontal)):with open(ToFilePath,'a') as ToFileObj:FileInfo = x.get_text()print(FileInfo)ToFileObj.write(FileInfo)SourceFilePath = "民法典.pdf"ToFilePath = "test.txt"ReadPDF(SourceFilePath,ToFilePath)

二,使用Python提取PDF中的图片

#coding=utf-8import fitzimport timeimport reimport osdef pdf2pic(path, pic_path):t0 = time.time()# 生成图片初始时间checkXO = r"/Type(?= */XObject)" # 使用正则表达式来查找图片checkIM = r"/Subtype(?= */Image)"doc = fitz.open(path) # 打开pdf文件imgcount = 0 # 图片计数lenXREF = doc._getXrefLength() # 获取对象数量长度# 打印PDF的信息print("文件名:{}, 页数: {}, 对象: {}".format(path, len(doc), lenXREF - 1))# 遍历每一个对象for i in range(1, lenXREF):text = doc._getXrefString(i) # 定义对象字符串isXObject = re.search(checkXO, text) # 使用正则表达式查看是否是对象isImage = re.search(checkIM, text)# 使用正则表达式查看是否是图片if not isXObject or not isImage: # 如果不是对象也不是图片,则continuecontinueimgcount += 1pix = fitz.Pixmap(doc, i)# 生成图像对象new_name = "图片{}.png".format(imgcount) # 生成图片的名称if pix.n < 5: # 如果pix.n<5,可以直接存为PNGpix.writePNG(os.path.join(pic_path, new_name))else:# 否则先转换CMYKpix0 = fitz.Pixmap(fitz.csRGB, pix)pix0.writePNG(os.path.join(pic_path, new_name))pix0 = Nonepix = None# 释放资源t1 = time.time() # 图片完成时间print("运行时间:{}s".format(t1 - t0))print("提取了{}张图片".format(imgcount))if __name__=='__main__':path = r"开通Carplay教程.pdf"pic_path = os.getcwd()+"\\图片"# 创建保存图片的文件夹if os.path.exists(pic_path):print("文件夹已存在,不必重新创建!")passelse:os.mkdir(pic_path)pdf2pic(path, pic_path)

需要注意的是,fitz 模块需要 Microsoft Visual C++ 14版本支持,因此还需要安装此软件,放上此软件的下载地址

/b01tsod7i 密码:gkbi

之后运行时还会报错,ModuleNotFoundError: No module named ‘frontend’,此时需要执行命令

pip install PyMuPDF

代码即可运行

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。