【问题标题】:extracting text from pdf - PyPDF2从 pdf 中提取文本 - PyPDF2
【发布时间】:2019-09-10 23:19:14
【问题描述】:

我正在按照页面上的教程从 pdf 中提取文本:

http://www.blog.pythonlibrary.org/2018/06/07/an-intro-to-pypdf2/

而且我可以打印 pdf 信息,但我不能打印页面的内容。它不会抛出任何错误,但我也看不到 pdf 的文本

可能是什么问题?

from PyPDF2 import PdfFileReader


def get_info(path):
    with open(path, 'rb') as f:
        pdf = PdfFileReader(f)
        info = pdf.getDocumentInfo()
        number_of_pages = pdf.getNumPages()

    #print(info)

    author = info.author
    creator = info.creator
    producer = info.producer
    subject = info.subject
    title = info.title


    print(author)
    print(creator)
    print(producer)
    print(subject)
    print(title)

def text_extractor(path):
    with open(path, 'rb') as f:
        pdf = PdfFileReader(f)

        # get the first page
        page = pdf.getPage(0)
        print(page)
        print('Page type: {}'.format(str(type(page))))

        text = page.extractText()

        print(text) #THIS PART SHOULD PRINT TEXT FROM PDF, BUT DOESNT WORK



if __name__ == '__main__':
        #URL PDF: https://oficinavirtual.ugr.es/apli/solicitudPAU/test.pdf
    path = 'test.pdf'
    get_info(path)
    print("\n"*2)
    text_extractor(path)

【问题讨论】:

  • 您的代码对我来说很好用。这可能来自您正在使用的文件(也许第一页是空的?)。此外,我使用 PyPDF2 已经有一段时间了,它并不是万无一失的:使用旧版本的 Adob​​e 编码或从奇怪格式转换的 pdf 可能无法工作、抛出异常或只是返回乱码。所以用不同的文件测试你的代码,并使用 try/except。

标签: python-3.x pypdf2


【解决方案1】:

虽然这不是解决方案,但您可以简单地使用 pip 安装 pdfminer3 并使用最小的可重现示例 here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-05
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 2013-12-18
    相关资源
    最近更新 更多