首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在从pdf中提取文本时忽略表格及其内容

如何在从pdf中提取文本时忽略表格及其内容
EN

Stack Overflow用户
提问于 2021-05-04 15:29:28
回答 1查看 339关注 0票数 0

到目前为止,我已经成功地从pdf文件中提取了文本内容。我不得不在表外提取文本内容(忽略表及其内容),并且需要帮助

该文件可从here下载

代码语言:javascript
运行
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2021-05-13 21:52:57

对于您共享的PDF,您可以使用以下代码来提取表外的文本

代码语言:javascript
运行
复制
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(...)中)的边界框内的所有对象,并创建页面的过滤版本,其中将只包含那些位于任意表之外的对象。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67380474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档