【问题标题】:Print to excel first line of each page in pdf file打印到pdf文件中每一页的excel第一行
【发布时间】:2020-11-05 21:49:46
【问题描述】:

我是 python 新手,我身后只有一个脚本用于搜索 pdf 中的字符串。现在,我想构建脚本,它将在新的 CSV/xlsx 文件中给出结果,其中我将有第一行及其给定 pdf 文件的页码。现在我有下面的代码来打印整个页面:

from PyPDF2 import PdfFileReader

pdf_document = "example.pdf"
with open(pdf_document, "rb") as filehandle:
    pdf = PdfFileReader(filehandle)
    info = pdf.getDocumentInfo()
    pages = pdf.getNumPages()
    print (info)
    print ("number of pages: %i" % pages)
    page1 = pdf.getPage(0)
    print(page1)
    print(page1.extractText())

【问题讨论】:

    标签: python python-3.x csv pdf pypdf2


    【解决方案1】:

    您可以逐页读取pdf文件,用'\n'分割(如果那是分割行的字符),然后使用CSV包写入CSV文件。像下面这样的脚本。顺便提一下,如果 PDF 包含图像,则此代码将无法提取文本。您需要一个 OCR 模块首先将图像转换为文本。

    from PyPDF2 import PdfFileReader
    import csv
    
    pdf_document = "test.pdf"
    with open(pdf_document, "rb") as filehandle:
        pdf = PdfFileReader(filehandle)
        with open('result.csv','w') as csv_file:
            csv_writer = csv.writer(csv_file)
            csv_writer.writerow(['page numebr','firts line'])
            for i in range(0, pdf.getNumPages()):
                content= pdf.getPage(i).extractText().split('\n')
                print(content[0]) # prints first line
                print(i+1) # prints page number
                print('-------------')
                csv_writer.writerow([i+1,content[0]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-09
      • 2022-01-06
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      • 1970-01-01
      • 2013-10-09
      相关资源
      最近更新 更多