用Python替代Adobe,零成本從PDF提取數(shù)據(jù)
一、簡介
PDF文件是官方報(bào)告、發(fā)票和數(shù)據(jù)表的通用語言,然而從PDF文件中提取表格數(shù)據(jù)可能是一項(xiàng)挑戰(zhàn)。盡管Adobe Acrobat等工具提供了解決方案,但它們并不總是易于獲取或可自動(dòng)化運(yùn)行,而Python則是編程語言中的瑞士軍刀。本文將探討如何利用Python輕松實(shí)現(xiàn)PDF數(shù)據(jù)提取,而無需使用昂貴的軟件。
二、了解挑戰(zhàn)
PDF文件是為展示而設(shè)計(jì)的,而不是為提取數(shù)據(jù)。它們通常包含復(fù)雜的布局,在視覺上很吸引人,但在計(jì)算上卻無法訪問。因此,提取表格等結(jié)構(gòu)化信息非常困難。
三、使用PyMuPDF提取文本
PyMuPDF是一款輕量級(jí)的庫,擅長讀取PDF文件并提取文本。只需幾行代碼,就可以讀取PDF并從任意頁面提取文本。本文從奔馳集團(tuán)2022年第四季度年度報(bào)告中提取“股東權(quán)益變動(dòng)綜合報(bào)表(Consolidated Statement of Changes in Equity)”,代碼如下。
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
# 定義感興趣區(qū)域的矩形(不包括腳注)
non_footnote_area_height = page_height * 0.90
clip_rect = fitz.Rect(0, 0, page_width, non_footnote_area_height)
# 從定義的區(qū)域提取文本
page_text = page.get_text("text", clip=clip_rect)
lines_page = page_text.strip().split('\n')
四、規(guī)整數(shù)據(jù)
提取的文本通常帶有不需要的字符或格式。這就是預(yù)處理發(fā)揮作用的地方。Python的字符串處理功能使用戶能夠清洗和準(zhǔn)備數(shù)據(jù)以轉(zhuǎn)換為表格格式。
# --- 數(shù)據(jù)清洗 ---
# 定義要搜索的字符串并查找其索引
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 = []
# 如果不是數(shù)字或連字符,則合并連續(xù)字符串條目
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)
五、使用Pandas創(chuàng)建表格
一旦數(shù)據(jù)清洗完成,就可以使用pandas了。這個(gè)功能強(qiáng)大的數(shù)據(jù)分析庫可以將一系列數(shù)據(jù)點(diǎn)轉(zhuǎn)換為DataFrame,即一個(gè)二維的、大小可變的、可能是異構(gòu)的帶有標(biāo)記軸的表格數(shù)據(jù)結(jié)構(gòu)。
# --- 創(chuàng)建DataFrame ---
# 根據(jù)列數(shù)將清洗后的數(shù)據(jù)分割成塊
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'
]
# 使用數(shù)據(jù)塊和表頭創(chuàng)建DataFrame
financial_df = pd.DataFrame(data_chunks, columns=headers)
# Display the head of the DataFrame to verify its structure
financial_df.head()
如下所示是從PDF文件中提取的表格結(jié)果。
圖片
六、結(jié)語
通過利用Python強(qiáng)大的庫,可以自動(dòng)化繁瑣的PDF數(shù)據(jù)提取任務(wù)。這種方法不僅成本低,而且提供了Python開發(fā)者所喜愛的靈活性和強(qiáng)大功能。