【问题标题】:How to ignore table and its content while extracting text from pdf从pdf中提取文本时如何忽略表格及其内容
【发布时间】:2021-05-04 07:29:28
【问题描述】:

到目前为止,我已成功从 pdf 文件中提取文本内容。我被困在必须提取表格之外的文本内容(忽略表格及其内容)并需要帮助的地步

PDF可以从here下载

import pdfplumber
pdfinstance = pdfplumber.open(r'\List of Reportable Jurisdictions for 2020 CRS information reporting_9 Feb.pdf')

for epage in range(len(pdfinstance.pages)):
    page = pdfinstance.pages[epage]
    text = page.extract_text(x_tolerance=3, y_tolerance=3)
    print(text)

【问题讨论】:

    标签: python pdf pdfplumber


    【解决方案1】:

    对于您分享的PDF,可以使用以下代码提取表格外的文字

    import pdfplumber
    
    
    def not_within_bboxes(obj):
        """Check if the object is in any of the table's bbox."""
    
        def obj_in_bbox(_bbox):
            """See https://github.com/jsvine/pdfplumber/blob/stable/pdfplumber/table.py#L404"""
            v_mid = (obj["top"] + obj["bottom"]) / 2
            h_mid = (obj["x0"] + obj["x1"]) / 2
            x0, top, x1, bottom = _bbox
            return (h_mid >= x0) and (h_mid < x1) and (v_mid >= top) and (v_mid < bottom)
    
        return not any(obj_in_bbox(__bbox) for __bbox in bboxes)
    
    
    with pdfplumber.open("file.pdf") as pdf:
        for page in pdf.pages:
            print("\n\n\n\n\nAll text:")
            print(page.extract_text())
    
            # Get the bounding boxes of the tables on the page.
            bboxes = [
                table.bbox
                for table in page.find_tables(
                    table_settings={
                        "vertical_strategy": "explicit",
                        "horizontal_strategy": "explicit",
                        "explicit_vertical_lines": page.curves + page.edges,
                        "explicit_horizontal_lines": page.curves + page.edges,
                    }
                )
            ]
    
            print("\n\n\n\n\nText outside the tables:")
            print(page.filter(not_within_bboxes).extract_text())
    

    我正在使用pdfplumber 提供的.filter() 方法删除任何落在任何表(在not_within_bboxes(...) 中)的边界框内的对象,并创建页面的过滤版本,该版本将只包含那些位于任何表格之外的对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-12
      • 2013-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-01
      • 1970-01-01
      • 2020-04-08
      相关资源
      最近更新 更多