【问题标题】:How to get text from local PDF file using Python如何使用 Python 从本地 PDF 文件中获取文本
【发布时间】:2020-07-30 14:40:44
【问题描述】:

请不要使用“tika”作为答案。 我已经尝试过这个问题的答案:

How to extract text from a PDF file?

我有这个 PDF 文件,https://drive.google.com/file/d/1aUfQAlvq5hA9kz2c9CyJADiY3KpY3-Vn/view?usp=sharing,我想复制文本。

import PyPDF2
pdfFileObject = open('C:\\Path\\To\\Local\\File\\Test_PDF.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObject)
count = pdfReader.numPages
for i in range(count):
    page = pdfReader.getPage(i)
    print(page.extractText())

输出为“Date Submitted: 2019-10-21 16:03:36.093 | Form Key: 5544”,这只是文本的一部分。下一行文本以“Exhibit A to RFA....”开头

【问题讨论】:

  • 您能解释一下which is only part of the text 的意思吗?阅读器逐行读取,因此它给出了正确的顺序输出。
  • @AzyCrw4282 我正在尝试获取 PDF 中的所有文本,而不仅仅是第一行。

标签: python pdf


【解决方案1】:

我自己从未使用过PYPDF2,因此无法真正输入我的知识来找出到底出了什么问题。但是来自documentation 的以下内容说明了有关extractText() 功能的以下内容

按照内容流中提供的顺序找到所有文本绘制命令,然后提取文本。 这适用于某些 PDF 文件,但对其他文件效果不佳,具体取决于所使用的生成器。这将在未来进行完善。不要依赖从这个函数出来的文本的顺序,因为如果这个函数变得更复杂,它会改变。

这是一个 alternative way 来解决这个问题,并解释可能出了什么问题。我还建议使用pdftotext。这对我来说已经多次可靠地工作了;这个answer 也会对此有所帮助。

【讨论】:

  • 感谢这让我走上了正轨。很快发布我的答案。 pip install pdfminer.six 是关键。
  • 很好,乐于助人
【解决方案2】:

找到了解决办法。

#pip install pdfminer.six
import io

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage


def convert_pdf_to_txt(path):
    '''Convert pdf content from a file path to text

    :path the file path
    '''
    rsrcmgr = PDFResourceManager()
    codec = 'utf-8'
    laparams = LAParams()

    with io.StringIO() as retstr:
        with TextConverter(rsrcmgr, retstr, codec=codec,
                           laparams=laparams) as device:
            with open(path, 'rb') as fp:
                interpreter = PDFPageInterpreter(rsrcmgr, device)
                password = ""
                maxpages = 0
                caching = True
                pagenos = set()

                for page in PDFPage.get_pages(fp,
                                              pagenos,
                                              maxpages=maxpages,
                                              password=password,
                                              caching=caching,
                                              check_extractable=True):
                    interpreter.process_page(page)

                return retstr.getvalue()


if __name__ == "__main__":
    print(convert_pdf_to_txt('C:\\Path\\To\\Test_PDF.pdf'))

【讨论】:

    猜你喜欢
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2019-03-16
    • 1970-01-01
    • 2014-12-17
    相关资源
    最近更新 更多