如何使用 pdfplumber 从 PDF 中提取半结构化表格

问题描述 投票:0回答:1

我想从 PDF 文件中提取半结构化表格。如果其他模块可以更好地工作,我可能会考虑除 pdfplumber 之外的其他模块。我不仅需要表格,而且有时表格上方的文本仍然是表格的一部分(例如列名有时在表格上方),或者表格在另一页上继续。

我尝试使用 extract_text_lines() ,效果很好。我想逐行检查 pdf,如果该行是一个表格 - 我开始收集这些数据。

def extract_table_from_page(pdf_path, page_number):

    with pdfplumber.open(pdf_path) as pdf:

        page = pdf.pages[page_number]
        lines = page.extract_text_lines()
        for line in lines:
            if 'chars' in line.keys():
                print(line)

python pdf extract pdfplumber
1个回答
0
投票

这是具有外部列标题的表格示例。

一些列名称是垂直的。

这是一个 PyMuPDF 脚本,它查找并提取表,识别列名称并以 Markdown 格式打印表内容(Github 兼容):

import fitz  # PyMuPDF
doc=fitz.open("input.pdf")  # test file
page=doc[0]  # first page having the table
tabs=page.find_tables()  # find tables on page
tab=tabs[0]  # take first table
print(tab.to_markdown())  # print all content in Github-markdown format

|Column1|column2|column3|column4|
|---|---|---|---|
|11|22|33|44|
|55|66|77|88|
|99|AA|BB|CC|
|DD|EE|FF||

tab.header.external  # show some table header properties
True

tab.header.names
['Column1', 'column2', 'column3', 'column4']
© www.soinside.com 2019 - 2024. All rights reserved.