最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

PyPDF2讀取PDF文件內(nèi)容保存到本地TXT實(shí)例

 更新時(shí)間:2020年05月12日 14:56:02   作者:Luzaofa  
這篇文章主要介紹了PyPDF2讀取PDF文件內(nèi)容保存到本地TXT實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

我就廢話不多說(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è)并將其寫入新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è)并將其寫入新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])

方法二:在寫入新文件時(shí)使用if判斷進(jìn)行篩選出不要的頁(yè)面

想法一、將讀取與寫入同時(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è)并將其寫入新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)存,最后在寫入,來(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è)并將其寫入新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)存,最后寫入,提高處理速度
        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)存,最后寫入文件
  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è)并將其寫入新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)存,最后寫入,提高處理速度
        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è)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python的pygame安裝教程詳解

    Python的pygame安裝教程詳解

    Pygame是跨平臺(tái)Pyth,Pygame 作者是 Pete Shinners, 協(xié)議為 GNU Lesser General Public License。這篇文章主要介紹了Python的pygame安裝教程,需要的朋友可以參考下
    2020-02-02
  • Pygame實(shí)戰(zhàn)練習(xí)之保護(hù)單身狗游戲

    Pygame實(shí)戰(zhàn)練習(xí)之保護(hù)單身狗游戲

    下面這篇文章主要給大家介紹了關(guān)于如何利用python寫一個(gè)簡(jiǎn)單的由經(jīng)典躲避類益智小游戲修改的保護(hù)單身狗游戲的相關(guān)資料,需要的朋友可以參考下
    2021-09-09
  • 詳解用python -m http.server搭一個(gè)簡(jiǎn)易的本地局域網(wǎng)

    詳解用python -m http.server搭一個(gè)簡(jiǎn)易的本地局域網(wǎng)

    這篇文章主要介紹了詳解用python -m http.server搭一個(gè)簡(jiǎn)易的本地局域網(wǎng),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • Python?操作?MongoDB數(shù)據(jù)庫(kù)的方法(非?ODM)

    Python?操作?MongoDB數(shù)據(jù)庫(kù)的方法(非?ODM)

    這篇文章主要介紹了Python?操作?MongoDB?----非?ODM的方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-03-03
  • python 字符串格式化代碼

    python 字符串格式化代碼

    python 字符串格式化代碼,需要的朋友可以參考一下
    2013-03-03
  • Python3實(shí)現(xiàn)監(jiān)控新型冠狀病毒肺炎疫情的示例代碼

    Python3實(shí)現(xiàn)監(jiān)控新型冠狀病毒肺炎疫情的示例代碼

    這篇文章主要介紹了Python3實(shí)現(xiàn)監(jiān)控新型冠狀病毒肺炎疫情的示例代碼,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-02-02
  • Python實(shí)現(xiàn)上下班搶個(gè)順風(fēng)單腳本

    Python實(shí)現(xiàn)上下班搶個(gè)順風(fēng)單腳本

    這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)上下班搶個(gè)順風(fēng)單腳本,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-02-02
  • 寫了個(gè)監(jiān)控nginx進(jìn)程的Python腳本

    寫了個(gè)監(jiān)控nginx進(jìn)程的Python腳本

    接上一文用iptables讓SSH服務(wù)對(duì)陌生人說(shuō)不。還是有點(diǎn)擔(dān)心這個(gè)學(xué)期內(nèi),nginx可能會(huì)因?yàn)橄到y(tǒng)各種原因而出現(xiàn)異常退出,導(dǎo)致Web服務(wù)暫停。所以,又來(lái)了一個(gè)方案
    2012-05-05
  • Python鏈表排序相關(guān)問(wèn)題解法示例

    Python鏈表排序相關(guān)問(wèn)題解法示例

    這篇文章主要為大家介紹了Python鏈表排序相關(guān)問(wèn)題解法示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01
  • python的random和time模塊詳解

    python的random和time模塊詳解

    這篇文章主要介紹了python的random和time模塊,具有一定借鑒價(jià)值,需要的朋友可以參考下,希望能夠給你帶來(lái)幫助
    2021-10-10

最新評(píng)論

扶绥县| 青州市| 龙州县| 衡南县| 同德县| 浮山县| 调兵山市| 台州市| 阳江市| 绥芬河市| 厦门市| 黑龙江省| 崇义县| 临安市| 兴海县| 泰安市| 米脂县| 进贤县| 曲阳县| 原阳县| 镇康县| 连城县| 鲁甸县| 德惠市| 桦川县| 封丘县| 德阳市| 镇原县| 台中县| 云林县| 深州市| 赞皇县| 洛南县| 沧源| 红桥区| 香港 | 商都县| 台南市| 望都县| 闻喜县| 图木舒克市|