> ## Content Index
> Fetch the complete content index at: https://www.hubwiz.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# 3个最有效的表格提取SDK
- URL: https://www.hubwiz.com/blog/top3-table-extraction-sdks/
- Published: 2024-12-28T01:34:27.000Z
- Updated: 2024-12-28T01:34:27.000Z
- Description: 在本文中，我们将研究用于表格数据提取的各种工具和技术，并将指导你完成有效实施这些解决方案所需的 Python 代码。
- Author: admin
- Tags: LIBRARY, TABLE EXTRACTION, PYMUPDF, PILLOW, AZURE DOCUMENT AI, PADDLEOCR, PANDAS, OPENPYXL, OPENCV, #Import 2026-10-14 14:41

本文深入探讨了从表格中提取数据的微妙世界，这项任务比提取纯文本要复杂得多。这种复杂性源于表格中经常出现的非常规结构，尤其是在研究论文中。与标准表格不同，这些表格可能没有清晰的界定，或者列标题和内容之间可能存在错位。这种半结构化表格对传统的提取方法提出了挑战，需要更高级的方法。

本文重点介绍旨在有效应对这些挑战的免费开源工具和技术。它探讨了处理非标准表格格式的各种策略，提供了有效提取数据的见解，即使是从格式最不规则的表格中也是如此。重点是提供实用、可访问的解决方案，这些解决方案可以处理表格数据提取的复杂性，而无需承担高昂的成本。通过这种探索，本文旨在让读者掌握在传统方法无法满足需求的世界中应对表格数据提取的知识。

在本文中，我们将研究用于表格数据提取的各种工具和技术，并将指导你完成有效实施这些解决方案所需的 Python 代码。

## 1、PDF 到图像转换（用于 OCR 工具）

我们探索一种基于 Python 的方法，用于将 PDF 文档转换为图像，这是使用 OCR（光学字符识别）工具的关键步骤。此过程涉及 PyMuPDF 库（称为 fitz）和 Python 图像库 (PIL)。提供的脚本将每个 PDF 页面转换为 PNG 图像，使其可供 OCR 软件读取。该方法保留 PDF 的原始布局和内容，确保准确的 OCR 结果。这种高效的技术对于从基于图像的文档中提取文本数据至关重要。

这是上述任务的示例 Python 脚本：

```
import fitz  # PyMuPDF
from PIL import Image

def pdf_to_png(pdf_path, output_folder):
    pdf_document = fitz.open(pdf_path)

    for page_number in range(pdf_document.page_count):
        page = pdf_document.load_page(page_number)

        pixmap = page.get_pixmap()

        image = Image.frombytes("RGB", [pixmap.width, pixmap.height], pixmap.samples)

        image.save(f"{output_folder}/page_{page_number + 1}.png")

    pdf_document.close()

pdf_path = "doc1.pdf"
output_folder = "doc1"

pdf_to_png(pdf_path, output_folder)
```

## 2、Azure 文档智能布局模型

我们专注于利用 Azure 的功能进行表格数据提取。虽然 Azure 允许直接输入 PDF，但免费版本限制每个事务两页。为了避免这种情况，建议将 PDF 转换为图像。此过程必不可少的是 Azure API 密钥和 Endpoint 密钥；有关获取这些内容的详细说明，请参阅 [Microsoft 的文档页面](https://learn.microsoft.com/en-us/azure/ai-services/document-intelligence/create-document-intelligence-resource?view=doc-intel-4.0.0&ref=hubwiz.com)。我们的方法采用了 Azure 布局模型和 Python SDK，为分析文档结构和高效提取表格数据（即使是从复杂的布局中）提供了强大的解决方案。

这是上述任务的示例 Python 脚本：

```
import os
from azure.ai.formrecognizer import DocumentAnalysisClient
from azure.core.credentials import AzureKeyCredential
import pandas as pd

# Azure API and Endpoint keys
API_KEY = "your_api_key"
ENDPOINT = "your_endpoint_url"

# Assigning your Azure key and endpoint to variables
key = API_KEY
endpoint = ENDPOINT

# Function to analyze layout of the document
def analyze_layout(local_file_path):
    # Initializing the Document Analysis Client with endpoint and key
    document_analysis_client = DocumentAnalysisClient(
        endpoint=endpoint, credential=AzureKeyCredential(key)
    )

    # Opening the file and analyzing the layout
    with open(local_file_path, "rb") as f:
        poller = document_analysis_client.begin_analyze_document(
            "prebuilt-layout", document=f
        )
        result = poller.result()
    return result

# Function to extract table data from the result
def extract_table_data(result):
    tables = []
    for table in result.tables:
        rows = []
        for cell in table.cells:
            while len(rows) <= cell.row_index:
                rows.append([])
            rows[cell.row_index].append(cell.content)
        tables.append(rows)
    return tables

# Convert the extracted tables into pandas dataframes
def tables_to_dataframes(tables):
    dataframes = [pd.DataFrame(table) for table in tables]
    return dataframes

# Function to save the tables in CSV and Excel format
def save_tables(dataframes, base_filename):
    for i, df in enumerate(dataframes):
        csv_filename = f"outputs/{base_filename}_table_{i}.csv"
        xlsx_filename = f"outputs/{base_filename}_table_{i}.xlsx"
        df.to_csv(csv_filename, index=False)
        df.to_excel(xlsx_filename, index=False)

# Main execution block
if __name__ == "__main__":
    directory_path = "inputs" # Input directory

    # Loop through each file in the directory
    for filename in os.listdir(directory_path):
        if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.pdf')):
            file_path = os.path.join(directory_path, filename)
            print(f"Analyzing {filename}...")
            result = analyze_layout(file_path)

            tables = extract_table_data(result)
            dataframes = tables_to_dataframes(tables)
            save_tables(dataframes, os.path.splitext(filename)[0])

            print(f"Completed analysis for {filename}")
```

在可用的表格提取工具中，Azure 布局模型通常提供最准确的结果。

这是使用 Azure document AI 提取半结构化表格的原图和结果：

![](https://www.hubwiz.com/blog/content/images/2024/12/image-781.png)

表格原图

![](https://www.hubwiz.com/blog/content/images/2024/12/image-783.png)

提取结果

如你所见，提取过程中存在一些不一致之处。但是，大多数提取都是准确的，与其他方法相比，这些结果达到了可接受的水平。值得一提的是，Azure Document AI 可用于广泛的 OCR 相关任务，我稍后会写另一篇文章，介绍使用发票模型和自定义模型提取账单和发票数据。

## 3、PaddleOCR

PaddleOCR 是一款完全免费的开源工具包，在表格数据提取方面脱颖而出。它提供了广泛的预训练模型，使其适用于英语和中文语言提取。虽然它的准确性一般是可以接受的，但它可能不如 Azure 的工具那么精确。其功能的核心是 PP-Structure 组件，负责布局分析、表格检测和内容提取。这使得 PaddleOCR 成为各种基于文档和图像的文本提取的实用且易于访问的选择，特别是对于需要具有语言灵活性的经济高效解决方案的用户。

这是上述任务的示例 Python 脚本：

```
import cv2
import pandas as pd
from paddleocr import PPStructure
from openpyxl import load_workbook, Workbook
from openpyxl.drawing.image import Image as XLImage

# Initialize PPStructure for table extraction with recovery and OCR results
table_engine = PPStructure(recovery=True, return_ocr_result_in_table=True)

# Create and save an Excel workbook to store the results
output = '/content/output.xlsx'
Workbook().save(output)
book = load_workbook(output)
writer = pd.ExcelWriter(output, engine='openpyxl')
writer.book = book

# Process images in a loop
for n in range(1, 5):
    print('image', n)
    img_path = f'/content/{n} (1).png'
    img = cv2.imread(img_path)
    result = table_engine(img)

    # Create an image object for openpyxl
    xlimg = XLImage(img_path)

    i = 1
    for line in result:
        # Remove the 'img' key from the result
        line.pop('img')
        # Check if the line is a table
        if line.get("type") == "table":
            # Extract HTML table and convert to DataFrame
            html_table = line.get("res").get("html")
            html_data = pd.read_html(html_table)
            df = pd.DataFrame(html_data[0])

            # Write DataFrame to Excel and add the image to the sheet
            df.to_excel(writer, sheet_name=f"image {n} table {i}", index=1)
            book[f"image {n} table {i}"].add_image(xlimg, 'A100')
            i += 1

# Save the Excel workbook
writer.save()
```

这是使用 PaddleOCR 提取半结构化表格的原图和结果：

![](https://www.hubwiz.com/blog/content/images/2024/12/image-784.png)

表格原图

![](https://www.hubwiz.com/blog/content/images/2024/12/image-785.png)

表格提取结果

在这里我们可以看到结果不如 Azure AI 布局模型准确。但文本提取和边界框提取已正确完成。

## 4、PyMuPDF

PyMuPDF 是一款免费的开源工具，擅长从 PDF 中结构良好的表格中提取数据。它的优势在于处理具有传统表格布局的文档，使其成为标准数据提取任务的直接选择。然而，PyMuPDF 的性能可能会因研究论文中经常遇到的半结构化或非常规表格而下降。这些表格格式不规则，对 PyMuPDF 的传统方法构成了挑战。对于这种复杂的情况，使用具有深度学习功能的工具可能会更有效。它们经过训练可以处理更广泛的表格格式，提供为各种数据提取需求提供更通用的解决方案。

这是使用 PyMuPDF 进行表格数据提取的示例 Python 脚本：

```
import fitz  # PyMuPDF
import pandas as pd

def extract_tables_to_csv(pdf_path, output_folder):
    doc = fitz.open(pdf_path)

    for page_number in range(len(doc)):
        page = doc[page_number]
        tables = page.find_tables()  # detect the tables on the current page

        for i, table in enumerate(tables):
            try:
                df = table.to_pandas()  # attempt to convert the table to a pandas DataFrame
                csv_filename = f"{output_folder}/page_{page_number}_table_{i}.csv"
                df.to_csv(csv_filename, index=False)  # save the DataFrame as a CSV
            except IndexError as e:
                print(f"Error converting table on page {page_number}, table {i}: {e}")

    doc.close()

pdf_path = "test.pdf"
output_folder = "output"
extract_tables_to_csv(pdf_path, output_folder)
```

这是使用 PyMuPDF 提取结构良好的表格的原图和结果：

![](https://www.hubwiz.com/blog/content/images/2024/12/image-786.png)

表格原图

![](https://www.hubwiz.com/blog/content/images/2024/12/image-787.png)

提取结果

## 5、结束语

本文重点介绍了一系列用于表格数据提取的免费和开源工具，例如 PyMuPDF、PaddleOCR 和 Azure Document Intelligence，每个工具都有其优点和局限性。

重要的是要记住，表格数据提取既是一项深度学习挑战，也是一个活跃的研究领域，随着新的发展不断发展。 当前的解决方案提供了坚实的基础，但要获得尖端的准确性和多功能性，紧跟最新的深度学习进步是关键。

---

原文链接：[Automating Table Data Extraction: Tools and Techniques for Efficiency](https://medium.com/@malshanCS/automating-table-data-extraction-tools-and-techniques-for-efficiency-a29df313cbda?ref=hubwiz.com)

汇智网翻译整理，转载请标明出处