如何使用Python从pdf提取文本?

时间:2019-09-25 10:45:14

标签: python pdf text pdfminer

def extract_pdf(pdf_path):                     
    with open(pdf_path, 'rb') as fh:
    # iterate over all pages of PDF document
    for page in PDFPage.get_pages(fh, caching=True, check_extractable=True):
        # creating a resoure manager
        resource_manager = PDFResourceManager()

        # create a file handle
        fake_file_handle = StringIO()

        # creating a text converter object
        converter = TextConverter(
                            resource_manager, 
                            fake_file_handle, 
                            codec='utf-8', 
                            laparams=LAParams()
                    )

        # creating a page interpreter
        page_interpreter = PDFPageInterpreter(
                            resource_manager, 
                            converter
                        )

        # process current page
        page_interpreter.process_page(page)

        # extract text
        text = fake_file_handle.getvalue()
        yield text

        # close open handles
        converter.close()
        fake_file_handle.close()

text = ''
for page in extract_pdf('Path of the PDF Document'): 
    text +=  page

通过此代码,我可以提取许多PDF文档。但是,当我在互联网上的其他随机PDF上对其进行测试时,它开始波动,然后提取的文本就没有输出了。当我检查文本的类型时,它显示为<class 'str'>

有人可以纠正我在编写此代码时忽略的任何此类错误吗?

1 个答案:

答案 0 :(得分:1)

import PyPDF2 
o = open('example.pdf', 'rb') 
r = PyPDF2.PdfFileReader(o)
for page in range(r.numPages):
    Obj = r.getPage(page)
    print Obj.extractText()