Python提取PDF中的文字和图片
生活随笔
收集整理的這篇文章主要介紹了
Python提取PDF中的文字和图片
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一,使用Python提取PDF中的文字
# 只能處理包含文本的PDF文件 #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 LTTextBoxHorizontal,LAParams from pdfminer.pdfinterp import PDFTextExtractionNotAlloweddef ReadPDF(SourceFilePath,ToFilePath):# 以二進制形式打開PDF文件FileObj = open(SourceFilePath,"rb")# 創(chuàng)建一個PDF文檔分析器Parser = PDFParser(FileObj)# 創(chuàng)建PDF文檔PDFFile = PDFDocument()# 鏈接分析器與文檔對象Parser.set_document(PDFFile)PDFFile.set_parser(Parser)# 提供初始化密碼PDFFile.initialize()# 檢測文檔是否提供txt轉換if not PDFFile.is_extractable:raise PDFTextExtractionNotAllowedelse:# 解析數(shù)據(jù)# 數(shù)據(jù)管理器Manager = PDFResourceManager()# 創(chuàng)建一個PDF設備對象Laparams = LAParams()device = PDFPageAggregator(Manager,laparams = Laparams)# 創(chuàng)建解釋器對象Interpreter = PDFPageInterpreter(Manager,device)# 開始循環(huán)處理,每次處理一頁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-8 import fitz import time import re import os def pdf2pic(path, pic_path):t0 = time.time() # 生成圖片初始時間checkXO = r"/Type(?= */XObject)" # 使用正則表達式來查找圖片checkIM = r"/Subtype(?= */Image)"doc = fitz.open(path) # 打開pdf文件imgcount = 0 # 圖片計數(shù)lenXREF = doc._getXrefLength() # 獲取對象數(shù)量長度# 打印PDF的信息print("文件名:{}, 頁數(shù): {}, 對象: {}".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()+"\\圖片"# 創(chuàng)建保存圖片的文件夾if os.path.exists(pic_path):print("文件夾已存在,不必重新創(chuàng)建!")passelse:os.mkdir(pic_path)pdf2pic(path, pic_path)需要注意的是,fitz 模塊需要 Microsoft Visual C++ 14版本支持,因此還需要安裝此軟件,放上此軟件的下載地址
https://wws.lanzous.com/b01tsod7i 密碼:gkbi之后運行時還會報錯,ModuleNotFoundError: No module named ‘frontend’,此時需要執(zhí)行命令
pip install PyMuPDF代碼即可運行
總結
以上是生活随笔為你收集整理的Python提取PDF中的文字和图片的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 易语言 多线程 记录
- 下一篇: 电脑安装不了python3.50_Ana