Python 使用pdfminer.six从每个PDF页面提取文本

Python 使用pdfminer.six从每个PDF页面提取文本,python,parsing,pdf,pdfminer,Python,Parsing,Pdf,Pdfminer,pdfminer的文档充其量也很差。我最初使用的是pdfminer,它可以处理一些PDF文件,然后我遇到了一些bug,意识到我应该使用pdfminer.six 我想从PDF的每一页中提取文本,这样我就可以在哪里找到特定的单词等等 使用文档: from pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument from pdfminer.pdfpage import PDFPage from p

pdfminer的文档充其量也很差。我最初使用的是pdfminer,它可以处理一些PDF文件,然后我遇到了一些bug,意识到我应该使用pdfminer.six

我想从PDF的每一页中提取文本,这样我就可以在哪里找到特定的单词等等

使用文档:

from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfpage import PDFTextExtractionNotAllowed
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfdevice import PDFDevice

# Open a PDF file.
fp = open('mypdf.pdf', 'rb')
# Create a PDF parser object associated with the file object.
parser = PDFParser(fp)
# Create a PDF document object that stores the document structure.
# Supply the password for initialization.
document = PDFDocument(parser, password)
# Check if the document allows text extraction. If not, abort.
if not document.is_extractable:
    raise PDFTextExtractionNotAllowed
# Create a PDF resource manager object that stores shared resources.
rsrcmgr = PDFResourceManager()
# Create a PDF device object.
device = PDFDevice(rsrcmgr)
# Create a PDF interpreter object.
interpreter = PDFPageInterpreter(rsrcmgr, device)
# Process each page contained in the document.
for page in PDFPage.create_pages(document):
    interpreter.process_page(page)
我们已经解析了所有页面,但是没有关于如何从PDFpage中获取什么元素或任何内容的文档

我查看了PDFPage.py文件,寻找一种从每个PDF页面提取文本的方法,当然不是那么简单


使事情复杂化的是,pdfminer至少有3个版本,当然,随着时间的推移,它已经升级,因此我能找到的任何示例都不兼容。

这是我用于从pdf文件提取文本的版本

import io
from pdfminer.converter import TextConverter
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfpage import PDFPage


def extract_text_from_pdf(pdf_path):
    """
    This function extracts text from pdf file and return text as string.
    :param pdf_path: path to pdf file.
    :return: text string containing text of pdf.
    """
    resource_manager = PDFResourceManager()
    fake_file_handle = io.StringIO()
    converter = TextConverter(resource_manager, fake_file_handle)
    page_interpreter = PDFPageInterpreter(resource_manager, converter)

    with open(pdf_path, 'rb') as fh:
        for page in PDFPage.get_pages(fh, caching=True, check_extractable=True):
            page_interpreter.process_page(page)

        text = fake_file_handle.getvalue()

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

    if text:
        return text
    return None

不幸的是,它不起作用。我在Python3中使用pdfminer.six