使用Python将PDF转换为CSV

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

我的 pdf 文件有 25 多页。

我想将其转换为csv文件,我正在使用代码:

import tabula
tabula.convert_into("first.pdf", "output1.csv", output_format="csv", pages='all')

但是转换后,第一页仅给出一列,其中包含所有其他列的值,但从第二页开始,它是正确的。

列标题,分组为一个

转换为 csv 后第一页和第二页之间的差异

如何让输出正确?

python csv pdf tabula
1个回答
0
投票

我建议不要使用 tabula。 Tabula 具有 Java RuntTime 的外部依赖性。想想这意味着什么。假设您正在构建一个 docker 映像并希望将其部署到 AWS EKS、AWS ECS 等任何容器化平台。想想当您可以单独使用 python 时,利用图像中的 Java 层所需的额外开销。

解决方案1)

如果这不是一个机器学习项目,而您只是想提取这个特定的表并解析它,那么 Adobe 提供了一个名为 pdfservices-sdk 的 Python 包。它获取您的 pdf 文档并输出格式化的结构化 json 对象。代码如下所示:

import os
import os.path
import json

from adobe.pdfservices.operation.auth.credentials import Credentials
from adobe.pdfservices.operation.exception.exceptions import ServiceApiException, ServiceUsageException, SdkException
from adobe.pdfservices.operation.pdfops.options.extractpdf.extract_pdf_options import ExtractPDFOptions
from adobe.pdfservices.operation.pdfops.options.extractpdf.extract_element_type import ExtractElementType
from adobe.pdfservices.operation.execution_context import ExecutionContext
from adobe.pdfservices.operation.io.file_ref import FileRef
from adobe.pdfservices.operation.pdfops.extract_pdf_operation import ExtractPDFOperation

try:
    # get base path.
    # Initial setup, create credentials instance.
    credentials = Credentials.service_principal_credentials_builder(). \
        with_client_id('4fb491194b484bce9e8c06dd430eaeec'). \
        with_client_secret('p8e-jyP0pE4yywUt609dPwD5qeUIvst8Yf5Z'). \
        build()
    execution_context = ExecutionContext.create(credentials)
    extract_pdf_operation = ExtractPDFOperation.create_new()


    source = FileRef.create_from_local_file(os.path.join(os.getcwd(), 'table.pdf'))
    extract_pdf_operation.set_input(source)
    extract_pdf_options: ExtractPDFOptions = ExtractPDFOptions.builder() \
        .with_element_to_extract(ExtractElementType.TEXT) \
        .with_element_to_extract(ExtractElementType.TABLES) \
        .build()
    extract_pdf_operation.set_options(extract_pdf_options)

    result: FileRef = extract_pdf_operation.execute(execution_context)
    result.save_as(os.path.join(os.getcwd(), 'table_out.zip'))
except (ServiceApiException, ServiceUsageException, SdkException):
    pass

with open('table_out/structuredData.json', 'r') as f:
    reader = f.read()
    json_data = json.loads(reader)
    print(json_data)

我在使用此 pdf 文档时验证了此功能:https://www.w3.org/WAI/WCAG21/working-examples/pdf-table/table.pdf,因为您没有上传 pdf 文档。这里唯一值得注意的依赖项是您需要 Adobe Credential 密钥、client_id 和 client_secret,您可以将它们作为 pdfservices-api-credentials.json 存储在项目的根目录中。虽然这可行,但我也不推荐这种方法。不过,好处是您不需要安装 Java 并维护对完全不同的编程语言和运行时的巨大依赖。

解决方案2)

如果这是一个机器学习项目范围内的大型项目,您可以使用LangChain读取PDF文档,使用分块(文本块)转换文档,将文本块转换为文本嵌入,这将允许您工作与向量。一旦获得向量,就可以将向量存储到向量数据库中。在LangChain中,您可以使用基于变压器的LLM模型作为基础模型。您可以使用 Hugging Face 提供的开源库作为基础模型。如果您只是从 pdf 中提取表格来执行一次性任务,则此解决方案将显得有些过分。但是,如果这是更大的 LLM 计划的一部分,那么建议采用这种方法。

© www.soinside.com 2019 - 2024. All rights reserved.