PyPDF2讀取PDF文件內(nèi)容保存到本地TXT實(shí)例
我就廢話(huà)不多說(shuō)了,大家還是直接看代碼吧!
from PyPDF2.pdf import PdfFileReader import pandas as pd def Pdf_to_txt(pdf): for i in range(0, pdf.getNumPages()): title = [] lin1, lin2, lin3, lin4, lin5, lin6, lin7, lin8 = [], [], [], [], [], [], [], [] extractedText = pdf.getPage(i).extractText() text = extractedText.split('\n') num = 0 for lin in text: if num == 0: title.append(lin) elif num == 1: lin1.append(lin) elif num == 2: lin2.append(lin) elif num == 3: lin3.append(lin) elif num == 4: lin4.append(lin) elif num == 5: lin5.append(lin) elif num == 6: lin6.append(lin) elif num == 7: lin7.append(lin) elif num == 8: lin8.append(lin) num = 0 num += 1 Lin_num = len(lin8) data = {'Lin1': lin1[:Lin_num], 'Lin2': lin2[:Lin_num], 'Lin3': lin3[:Lin_num], 'Lin4': lin4[:Lin_num], 'Lin5': lin5[:Lin_num], 'Lin6': lin6[:Lin_num], 'Lin7': lin7[:Lin_num], 'Lin8': lin8[:Lin_num]} df = pd.DataFrame(data, columns=['Lin1', 'Lin2', 'Lin3', 'Lin4', 'Lin5', 'Lin6', 'Lin7', 'Lin8']) file_name = title[0] + '_page' + str((i + 1)) df.to_csv('tool/pdf解析/%s.txt' % file_name, index=False, sep='\t') if __name__ == '__main__': filename = 'E:/SVN/采集框架V2/analyse_code/政策/pdf/con026465.pdf' pdf = PdfFileReader(open(filename, "rb")) Pdf_to_txt(pdf)
補(bǔ)充知識(shí):使用PyPDF2庫(kù)對(duì)pdf文件進(jìn)行指定頁(yè)面刪除操作
平臺(tái):win10家庭版,python 3.7,PyPDF2
思維過(guò)程:
方法一:將pdf文件通過(guò)拆分為單頁(yè),放入一個(gè)文件夾,再刪除其中不要的文件,最后再把剩余的文件進(jìn)行合并為一個(gè)pdf文件
第一步:使用原文件路徑創(chuàng)建新文件夾,用于存放拆分后的單頁(yè)文件
def newdir(self,path): self.new = os.path.splitext(path)[0] if not os.path.isdir(self.new): #使用os.path.isdir判斷文件夾是否存在, os.mkdir(self.new)
第二步:生成單頁(yè)文件,并存放到新建的文件夾
def pdfsplt(self,path): if os.path.isfile(path): file_1 = open(path,"rb") file_reader = PyPDF2.PdfFileReader(file_1, strict=False) #使用strict關(guān)閉錯(cuò)誤提示 #使用for循環(huán)讀取每一頁(yè)并將其寫(xiě)入新pdf文件,文件以頁(yè)碼命名 for page in range(0,file_reader.getNumPages()): file_write = PyPDF2.PdfFileWriter() pageobj = file_reader.getPage(page) file_write.addPage(pageobj) output = str(self.new) + "\\" + str(int(page+1)) + ".pdf" with open(output,"wb") as output_pdf: file_write.write(output_pdf) file_1.close() else: print("文件不存在!") time.sleep(3) exit()
第三步:刪除文件夾中不要的文件
def pdfremove(self,number): for pag in number: filename = str(self.new) + "\\" + str(pag) + ".pdf" if os.path.isfile(filename): os.unlink(filename) else: print("請(qǐng)確認(rèn)要?jiǎng)h除的頁(yè)碼%s是否正確!!"%pag)
第四步:把剩余文件合并為一個(gè)pdf文件
def pdfmerge(self): file_list = [int(os.path.splitext(x)[0]) for x in os.listdir(self.new)] #讀取新建文件夾下的所有文件并提取文件名轉(zhuǎn)為數(shù)字 file_write = PyPDF2.PdfFileWriter() #先創(chuàng)建一個(gè)新的pdf對(duì)象 for page in sorted(file_list): pathstr = str(self.new) + "\\" + str(page) + ".pdf" file_1 = open(pathstr,"rb") file_reader = PyPDF2.PdfFileReader(file_1, strict=False) # 使用strict關(guān)閉錯(cuò)誤提示 pageobj = file_reader.getPage(0) file_write.addPage(pageobj) output = str(self.new) + "_new.pdf" with open(output, "wb") as output_pdf: file_write.write(output_pdf) print("第%s頁(yè)完成"%page) file_1.close()
第五步:刪除其中的緩存文件夾
def rmdir(self): if os.path.isdir(self.new): shutil.rmtree(self.new)
方法一的完整代碼:
import PyPDF2 import os,time,shutil,sys import threading class mypdf(object): def __init__(self,path,number): self.newdir(path) self.pdfsplt(path) self.pdfremove(number) self.pdfmerge() self.rmdir() pass #用于創(chuàng)建一個(gè)獨(dú)立的文件夾,存放緩存數(shù)據(jù) def newdir(self,path): self.new = os.path.splitext(path)[0] if not os.path.isdir(self.new): #使用os.path.isdir判斷文件夾是否存在, os.mkdir(self.new) #將每一頁(yè)生成獨(dú)立文件,存放到緩存文件夾 def pdfsplt(self,path): if os.path.isfile(path): file_1 = open(path,"rb") file_reader = PyPDF2.PdfFileReader(file_1, strict=False) #使用strict關(guān)閉錯(cuò)誤提示 #使用for循環(huán)讀取每一頁(yè)并將其寫(xiě)入新pdf文件,文件以頁(yè)碼命名 for page in range(0,file_reader.getNumPages()): file_write = PyPDF2.PdfFileWriter() pageobj = file_reader.getPage(page) file_write.addPage(pageobj) output = str(self.new) + "\\" + str(int(page+1)) + ".pdf" with open(output,"wb") as output_pdf: file_write.write(output_pdf) file_1.close() else: print("文件不存在!") time.sleep(3) exit() #刪除緩存文件夾中的不要的頁(yè) def pdfremove(self,number): for pag in number: filename = str(self.new) + "\\" + str(pag) + ".pdf" if os.path.isfile(filename): os.unlink(filename) else: print("請(qǐng)確認(rèn)要?jiǎng)h除的頁(yè)碼%s是否正確?。?%pag) #將緩存文件夾中的剩余文件合進(jìn)行合并 def pdfmerge(self): file_list = [int(os.path.splitext(x)[0]) for x in os.listdir(self.new)] #讀取新建文件夾下的所有文件并提取文件名轉(zhuǎn)為數(shù)字 file_write = PyPDF2.PdfFileWriter() #先創(chuàng)建一個(gè)新的pdf對(duì)象 for page in sorted(file_list): pathstr = str(self.new) + "\\" + str(page) + ".pdf" file_1 = open(pathstr,"rb") file_reader = PyPDF2.PdfFileReader(file_1, strict=False) # 使用strict關(guān)閉錯(cuò)誤提示 pageobj = file_reader.getPage(0) file_write.addPage(pageobj) output = str(self.new) + "_new.pdf" with open(output, "wb") as output_pdf: file_write.write(output_pdf) print("第%s頁(yè)完成"%page) file_1.close() def rmdir(self): if os.path.isdir(self.new): shutil.rmtree(self.new) if __name__ == "__main__": #通過(guò)第一個(gè)參數(shù)獲取待處理的文件,第二個(gè)參數(shù)到以后為刪除的頁(yè)碼 path = sys.argv[1] number = sys.argv[2:] mypdf = mypdf(path,number) def f(path,number): mypdf(path,number) threading.Thread(target=f,args=[path,number])
方法二:在寫(xiě)入新文件時(shí)使用if判斷進(jìn)行篩選出不要的頁(yè)面
想法一、將讀取與寫(xiě)入同時(shí)處理。使用if判斷篩選不要的頁(yè)面
def pdfsplt(self,path,number): print(number,type(number)) if os.path.isfile(path): file_1 = open(path,"rb") file_reader = PyPDF2.PdfFileReader(file_1, strict=False) #使用strict關(guān)閉錯(cuò)誤提示 file_write = PyPDF2.PdfFileWriter() #使用for循環(huán)讀取每一頁(yè)并將其寫(xiě)入新pdf文件,文件以頁(yè)碼命名 for page in range(0,file_reader.getNumPages()): if page not in number: pageobj = file_reader.getPage(page) file_write.addPage(pageobj) output = str(self.new) + "_new.pdf" with open(output,"wb") as output_pdf: file_write.write(output_pdf) file_1.close() else: print("文件不存在!") time.sleep(3) exit()
想法二、將數(shù)據(jù)先全部放入內(nèi)存,最后在寫(xiě)入,來(lái)提高速度:
def pdfsplt(self,path,number): print(number,type(number)) if os.path.isfile(path): file_1 = open(path,"rb") file_reader = PyPDF2.PdfFileReader(file_1, strict=False) #使用strict關(guān)閉錯(cuò)誤提示 file_write = PyPDF2.PdfFileWriter() #使用for循環(huán)讀取每一頁(yè)并將其寫(xiě)入新pdf文件,文件以頁(yè)碼命名 for page in range(0,file_reader.getNumPages()): if page not in number: pageobj = file_reader.getPage(page) file_write.addPage(pageobj) output = str(self.new) + "_new.pdf" with open(output,"wb") as output_pdf: #將內(nèi)容全部放入內(nèi)存,最后寫(xiě)入,提高處理速度 file_write.write(output_pdf) file_1.close() else: print("文件不存在!") time.sleep(3) exit()
方法二的完整代碼:
import PyPDF2 import os,time,shutil,sys import threading class mypdf(object): def __init__(self,path,number): self.new = os.path.splitext(path)[0] #獲取文件的路徑 self.pdfsplt(path,number) pass #循環(huán)每一頁(yè)讀入內(nèi)存,最后寫(xiě)入文件 def pdfsplt(self,path,number): print(number,type(number)) if os.path.isfile(path): file_1 = open(path,"rb") file_reader = PyPDF2.PdfFileReader(file_1, strict=False) #使用strict關(guān)閉錯(cuò)誤提示 file_write = PyPDF2.PdfFileWriter() #使用for循環(huán)讀取每一頁(yè)并將其寫(xiě)入新pdf文件,文件以頁(yè)碼命名 for page in range(0,file_reader.getNumPages()): if page not in number: pageobj = file_reader.getPage(page) file_write.addPage(pageobj) output = str(self.new) + "_new.pdf" with open(output,"wb") as output_pdf: #將內(nèi)容全部放入內(nèi)存,最后寫(xiě)入,提高處理速度 file_write.write(output_pdf) file_1.close() else: print("文件不存在!") time.sleep(3) exit() if __name__ == "__main__": #通過(guò)第一個(gè)參數(shù)獲取待處理的文件,第二個(gè)參數(shù)到以后為刪除的頁(yè)碼 path = sys.argv[1] number = sys.argv[2:] number = list(map(int, number)) mypdf = mypdf(path,number) def f(path,number): mypdf(path,number) threading.Thread(target=f,args=[path,number])
兩種方法的比較:
方法一 |
方法二中的第一種想法 |
方法二中的第二種想法 |
|
運(yùn)行速度 |
慢 |
較慢 |
快 |
代碼量 |
65行 |
34行 |
34行 |
缺點(diǎn):
方法一在處理掃描的pdf文件時(shí),運(yùn)行速度太慢,不能實(shí)現(xiàn)范圍性的刪除。
方法二不能實(shí)現(xiàn)范圍性的刪除
以上這篇PyPDF2讀取PDF文件內(nèi)容保存到本地TXT實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- Python使用PyPDF2庫(kù)實(shí)現(xiàn)向PDF文件中插入內(nèi)容
- Python利用PyPDF2庫(kù)實(shí)現(xiàn)輕松提取PDF文本
- Python使用PyPDF2?Pillow庫(kù)來(lái)將PDF文件轉(zhuǎn)圖片
- 解決pyPdf和pyPdf2在合并pdf時(shí)出現(xiàn)異常的問(wèn)題
- Python實(shí)現(xiàn)PyPDF2處理PDF文件的方法示例
- Python中使用pypdf2合并、分割、加密pdf文件的代碼詳解
- Python使用pdfplumber庫(kù)高效解析PDF文件
- Python利用pdfplumber庫(kù)提取pdf中表格數(shù)據(jù)
- python用pdfplumber提取pdf表格數(shù)據(jù)并保存到excel文件中
- Python利用pdfplumber實(shí)現(xiàn)讀取PDF寫(xiě)入Excel
- python使用PyPDF2 和 pdfplumber操作PDF文件
相關(guān)文章
pandas進(jìn)行時(shí)間數(shù)據(jù)的轉(zhuǎn)換和計(jì)算時(shí)間差并提取年月日
這篇文章主要介紹了pandas進(jìn)行時(shí)間數(shù)據(jù)的轉(zhuǎn)換和計(jì)算時(shí)間差并提取年月日,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07Python列表1~n輸出步長(zhǎng)為3的分組實(shí)例
這篇文章主要介紹了Python列表1~n輸出步長(zhǎng)為3的分組實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05詳解如何在pyqt中通過(guò)OpenCV實(shí)現(xiàn)對(duì)窗口的透視變換
這篇文章主要介紹了如何在pyqt中通過(guò)OpenCV實(shí)現(xiàn)對(duì)窗口的透視變換,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09對(duì)Python中DataFrame選擇某列值為XX的行實(shí)例詳解
今天小編就為大家分享一篇對(duì)Python中DataFrame選擇某列值為XX的行實(shí)例詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-01-01django之狀態(tài)保持-使用redis存儲(chǔ)session的例子
今天小編就為大家分享一篇django之狀態(tài)保持-使用redis存儲(chǔ)session的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07使用Python的SymPy庫(kù)解決數(shù)學(xué)運(yùn)算問(wèn)題的方法
這篇文章主要介紹了使用Python的SymPy庫(kù)解決數(shù)學(xué)運(yùn)算問(wèn)題的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-03-03Python+Selenium+Webdriver實(shí)現(xiàn)自動(dòng)執(zhí)行微軟獎(jiǎng)勵(lì)積分腳本
這篇文章主要為大家詳細(xì)介紹了如何利用Python+Selenium+Webdriver實(shí)現(xiàn)自動(dòng)執(zhí)行微軟獎(jiǎng)勵(lì)積分腳本,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2023-02-02Pytorch+PyG實(shí)現(xiàn)GraphSAGE過(guò)程示例詳解
這篇文章主要為大家介紹了Pytorch+PyG實(shí)現(xiàn)GraphSAGE過(guò)程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04聊聊boost?python3依賴(lài)安裝問(wèn)題
這篇文章主要介紹了boost?python3依賴(lài)安裝,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-12-12