从 pdf 中提取文本 - PyPDF2

Posted

技术标签:

【中文标题】从 pdf 中提取文本 - PyPDF2【英文标题】:extracting text from 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。 这能回答你的问题吗? Extract text from pdf converted from webpage using Pypdf2 【参考方案1】:

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

【讨论】:

以上是关于从 pdf 中提取文本 - PyPDF2的主要内容,如果未能解决你的问题,请参考以下文章

用python操作PDF文件

从 PDF 中提取文本 - 所有页面和输出 - 使用 Python 的文件

pdf及word文档的读取 pyPDF2,docx

PyPDF2如何实现按照PDF页码提取后并另存为PDF格式文件?

Python之精心整理的二十五个文本提取及NLP相关的处理案例

利用python去除pdf水印