Python替代Adobe从PDF提取数据

大家好,PDF文件是官方报告、发票和数据表的通用格式,然而从PDF文件中提取表格数据是一项挑战。尽管Adobe Acrobat等工具提供了解决方案,但它们并不总是易于获取或可自动化运行,而Python则是编程语言中的瑞士军刀。本文将探讨如何利用Python轻松实现PDF数据提取,而无需使用昂贵的软件。

1.使用PyMuPDF提取文本

PyMuPDF是一款轻量级的库,擅长读取PDF文件并提取文本。只需几行代码,就可以读取PDF并从任意页面提取文本。本文从奔驰集团2022年第四季度年度报告中提取"股东权益变动综合报表(Consolidated Statement of Changes in Equity)",代码如下:

python 复制代码
import fitz  
import pandas as pd
import re

# --- PDF处理 ---
# 定义PDF文件的路径并打开文档
pdf_path = '..../Merc 2022Q4 Rep.pdf'
pdf_document = fitz.open(pdf_path)

# 选择要阅读的特定页面
page = pdf_document[200]

# 获取页面的尺寸
page_rect = page.rect
page_width, page_height = page_rect.width, page_rect.height

# 定义感兴趣区域的矩形(不包括脚注)
non_footnote_area_height = page_height * 0.90
clip_rect = fitz.Rect(0, 0, page_width, non_footnote_area_height)

# 从定义的区域提取文本
page_text = page.get_text("text", clip=clip_rect)
lines_page = page_text.strip().split('\n')

2.规整数据

提取的文本通常带有不需要的字符或格式,这就是预处理发挥作用的地方。Python的字符串处理功能使用户能够清洗和准备数据以转换为表格格式。

python 复制代码
# --- 数据清洗 ---
# 定义要搜索的字符串并查找其索引
search_string = 'Balance at 1 January 2021 (restated) '
try:
    index = lines_page.index(search_string)
    data_lines = lines_page[index:]
except ValueError:
    print(f"The string '{search_string}' is not in the list.")
    data_lines = []

# 如果不是数字或连字符,则合并连续字符串条目
def combine_consecutive_strings(lines):
    combined = []
    buffer = ''
    
    for line in lines:
        if isinstance(line, str) and not re.match(r'^[-\d,.]+$', line.strip()):
            buffer += ' ' + line if buffer else line
        else:
            if buffer:
                combined.append(buffer)
                buffer = ''
            combined.append(line.strip())
    
    if buffer:
        combined.append(buffer)
    
    return combined

cleaned_data = combine_consecutive_strings(data_lines)

3.使用Pandas创建表格

一旦数据清洗完成,就可以使用pandas。这个功能强大的数据分析库可以将一系列数据点转换为DataFrame,即一个二维的、大小可变的、可能是异构的带有标记轴的表格数据结构。

python 复制代码
# --- 创建DataFrame ---
# 根据列数将清洗后的数据分割成块
num_columns = 6
data_chunks = [cleaned_data[i:i + num_columns] for i in range(0, len(cleaned_data), num_columns)]

# 定义DataFrame的表头
headers = [
    'Description',
    'Share capital',
    'Capital reserves',
    'Retained earnings (restated)',
    'Currency translation (restated)',
    'Equity instruments / Debt instruments'
]

# 使用数据块和表头创建DataFrame
financial_df = pd.DataFrame(data_chunks, columns=headers)

# Display the head of the DataFrame to verify its structure
financial_df.head()

如下所示是从PDF文件中提取的表格结果:

综上,通过利用Python强大的库,可以自动化繁琐的PDF数据提取任务。这种方法不仅成本低,而且提供了Python开发者所喜爱的灵活性和强大功能。

相关推荐
曲幽6 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户83562907805110 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
码路飞13 小时前
FastMCP 实战:一个 .py 文件,给 Claude Code 装上 3 个超实用工具
python·ai编程·mcp
dev派15 小时前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪17 小时前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户03321266636717 小时前
将 PDF 文档转换为图片【Python 教程】
python
悟空爬虫19 小时前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
dev派19 小时前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain
明月_清风21 小时前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽1 天前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic