python - 如何从pdf中提取带有缩进的文本?

标签 python python-3.x pdfminer

我想从 pdf 论文中提取文本。但是,当我使用下面的代码提取时,返回的文本类似于:

section text text text text text text text text
text text text text text text text text

但我希望该部分具有正常的缩进:

                 Section
text text text text text text text text
text text text text text text text text

遵循示例:

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_by_page(pdf_path):
    with open(pdf_path, 'rb') as fh:
        for page in PDFPage.get_pages(fh, 
                                      caching=True,
                                      check_extractable=True):
            resource_manager = PDFResourceManager()
            fake_file_handle = io.StringIO()
            converter = TextConverter(resource_manager, fake_file_handle)
            page_interpreter = PDFPageInterpreter(resource_manager, converter)
            page_interpreter.process_page(page)

            text = fake_file_handle.getvalue()
            yield text

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

def extract_text(pdf_path):
    for page in extract_text_by_page(pdf_path):
        print(page)
        print()

if __name__ == '__main__':
    print(extract_text('w9.pdf'))

可以用 pdfminer 做到这一点吗?

最佳答案

TextConverter 旨在将 pdf 转换为纯文本,而不考虑元素的位置。其背后的原因是,即使使用等宽字体,也很难使用纯文本准确呈现 pdf 中的文本位置。

HtmlConverterXMLConverter 输出一个包含文本和文本位置的文件。也许您可以使用此输出来创建您想要的结果。

如果您的需求更具体,您也可以考虑编写自己的PDFConverter。这使您可以控制一切,包括页面的开头和结尾、渲染图像、绘制多边形路径以及将文本写入特定位置。

关于python - 如何从pdf中提取带有缩进的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57990541/

相关文章:

python - 有没有一种在 Python 中使用二进制数的简单方法?

python - EbaySDK Python GetFeedback (ItemID) 仅返回 100 个值

python - 如何从 PDF 文件中提取文本和文本坐标?

python - 如何在 Anaconda 中安装 binstar 包?

python - PDFminer 空输出

python - 矢量化中的数组索引

python - 如何部署 Django 1.6、Python 3.3 和 Apache?

python-3.x - Python计算Grand Canonical Ensemble中的LennardJones 2D交互对相关分布函数

python - Flask:model_form:AttributeError:类型对象 'Form'没有属性 'query'

python - Subprocess.check_output 不起作用