本文介绍了在python中使用PDFMiner从PDF文件中提取文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找有关如何使用 PDFMiner 和 Python 从 PDF 文件中提取文本的文档示例.

I am looking for documentation or examples on how to extract text from a PDF file using PDFMiner with Python.

看起来 PDFMiner 更新了他们的 API,我发现的所有相关示例都包含过时的代码(类和方法已更改).我发现可以更轻松地从 PDF 文件中提取文本的库使用的是旧的 PDFMiner 语法,因此我不确定如何执行此操作.

It looks like PDFMiner updated their API and all the relevant examples I have found contain outdated code(classes and methods have changed). The libraries I have found that make the task of extracting text from a PDF file easier are using the old PDFMiner syntax so I'm not sure how to do this.

事实上,我只是在查看源代码,看看我是否能弄明白.

As it is, I'm just looking at source-code to see if I can figure it out.

推荐答案

这是一个使用当前版本的 PDFMiner(2016 年 9 月)从 PDF 文件中提取文本的工作示例

Here is a working example of extracting text from a PDF file using the current version of PDFMiner(September 2016)

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

def convert_pdf_to_txt(path):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = open(path, 'rb')
    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)

    text = retstr.getvalue()

    fp.close()
    device.close()
    retstr.close()
    return text

PDFMiner 的结构最近发生了变化,因此这应该适用于从 PDF 文件中提取文本.

PDFMiner's structure changed recently, so this should work for extracting text from the PDF files.

编辑:截至 2018 年 6 月 7 日仍在工作.已在 Python 3.x 版中验证

Edit : Still working as of the June 7th of 2018. Verified in Python Version 3.x

该解决方案适用于 2019 年 10 月 3 日的 Python 3.7.我使用了 2018 年 11 月发布的 Python 库 pdfminer.six.

The solution works with Python 3.7 at October 3, 2019. I used the Python library pdfminer.six, released on November 2018.

这篇关于在python中使用PDFMiner从PDF文件中提取文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 05:30