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开发者所喜爱的灵活性和强大功能。

相关推荐
电院工程师1 天前
SIMON64/128算法Verilog流水线实现(附Python实现)
python·嵌入式硬件·算法·密码学
学会用脚编程1 天前
word转Pdf,在window正常,放在linux服务器上就转出来中文是空白
pdf·word
Python图像识别1 天前
75_基于深度学习的咖啡叶片病害检测系统(yolo11、yolov8、yolov5+UI界面+Python项目源码+模型+标注好的数据集)
python·深度学习·yolo
闲人编程1 天前
Python游戏开发入门:Pygame实战
开发语言·python·游戏·pygame·毕设·codecapsule
机器学习算法与Python实战1 天前
最好的大模型训练、微调教程.pdf
pdf
CodeCraft Studio1 天前
PPT处理控件Aspose.Slides教程:使用Java将PowerPoint笔记导出为PDF
java·笔记·pdf·powerpoint·aspose·ppt转pdf·java将ppt导出pdf
深蓝电商API1 天前
告别混乱文本:基于深度学习的 PDF 与复杂版式文档信息抽取
人工智能·深度学习·pdf
雍凉明月夜1 天前
人工智能学习中深度学习之python基础之 类
python·学习
Geo_V1 天前
OpenAI 大模型 API 使用示例
python·chatgpt·openai·大模型应用·llm 开发
Hello_WOAIAI1 天前
2.4 python装饰器在 Web 框架和测试中的实战应用
开发语言·前端·python