Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用PDFMiner获取PDF中文本的位置?_Python_Pdf_Position_Pdfminer - Fatal编程技术网

Python 如何使用PDFMiner获取PDF中文本的位置?

Python 如何使用PDFMiner获取PDF中文本的位置?,python,pdf,position,pdfminer,Python,Pdf,Position,Pdfminer,PDFMiner的文档中说: PDFMiner允许用户获取文本在页面中的确切位置 然而,我一直无法找到如何做到这一点。PDFMiner的“文档”相当稀少,所以我不知道如何做到这一点 您正在查找每个布局对象上的bbox属性。PDFMiner文档中有一些关于的信息,但并没有涵盖所有内容 下面是一个例子: from pdfminer.pdfdocument import PDFDocument from pdfminer.pdfpage import PDFPage from pdfminer.pdf

PDFMiner的文档中说:

PDFMiner允许用户获取文本在页面中的确切位置


然而,我一直无法找到如何做到这一点。PDFMiner的“文档”相当稀少,所以我不知道如何做到这一点

您正在查找每个布局对象上的
bbox
属性。PDFMiner文档中有一些关于的信息,但并没有涵盖所有内容

下面是一个例子:

from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams, LTTextBox, LTTextLine, LTFigure


def parse_layout(layout):
    """Function to recursively parse the layout tree."""
    for lt_obj in layout:
        print(lt_obj.__class__.__name__)
        print(lt_obj.bbox)
        if isinstance(lt_obj, LTTextBox) or isinstance(lt_obj, LTTextLine):
            print(lt_obj.get_text())
        elif isinstance(lt_obj, LTFigure):
            parse_layout(lt_obj)  # Recursive


fp = open('example.pdf', 'rb')
parser = PDFParser(fp)
doc = PDFDocument(parser)

rsrcmgr = PDFResourceManager()
laparams = LAParams()
device = PDFPageAggregator(rsrcmgr, laparams=laparams)
interpreter = PDFPageInterpreter(rsrcmgr, device)
for page in PDFPage.create_pages(doc):
    interpreter.process_page(page)
    layout = device.get_result()
    parse_layout(layout)

如果您对单个
LTChar
对象的位置感兴趣,可以递归地解析到
LTTextBox
LTTextLine
的子布局对象中,就像上面示例中对
LTFigure
所做的一样。

1)您能解释一下LAParams()的功能吗?2) 尝试获取文本,然后尝试递归,而不是使用isinstance,这不是更像Python吗?除了LTFigure之外,没有其他类型的容器吗?LAParams包含用于布局分析的参数,该布局分析根据字符的位置将字符合并到单词和行中。您可以传递初始化参数,如line_overlap、char_margin、line_margin、word_margin、Box_flow、detect_vertical。有关说明和默认值,请参见PDFMiner文档。除了
LTFigure
之外,还有
LTTextBox
包含
LTTextLine
,后者依次包含
LTChar
LTAnno
。布局分析器有一个层次结构图。
LAParams
实际上只是修改布局分析器使用的参数的一种方法。即使只使用默认参数,也最好传递到
PDFPageAggregator
,否则可能无法执行某些布局分析。您可能可以使我的
parse_布局
函数更具python风格。每个
LT*
对象即使没有任何子对象也应该是可移植的,因此
LTFigure
isinstance检查可能是不必要的。类似地,您可以尝试对所有对象执行
get_text()
,如果未在该
LT*
对象上实现,则可以捕获失败。可能的