参考:
https://github.com/jsvine/pdfplumber?tab=readme-ov-file#extracting-tables
pdfplumber是怎么做表格抽取的
利用pdfplumber提取pdf文档内容
合合信息:表格识别与内容提炼技术理解及研发趋势
介绍
pdfplumber是一款完全用python开发的pdf解析库,基于pdfminer,可以获取每个字符,矩形框,线等对象具体信息,还可以抽取文本和表格。目前pdfplumber仅支持可编辑的pdf文档。
pdfplumber是一款完全用python开发的pdf解析库,对于全线表,pdfminer能够实现较好的抽取效果,但对于少线表和无线表,效果就差了很多。
示例:
import pdfplumber
with pdfplumber.open("example.pdf") as pdf:
first_page = pdf.pages[0]
table_settings = {"intersection_x_tolerance": 1}
table = first_page.extract_table(table_settings)
print(table)#列表
常用方法
extract_table()
是 pdfplumber
中用于从 PDF 中提取表格数据的函数。该函数可以接受一个可选的参数字典,用于更精细地控制表格数据的提取过程。下面介绍一些常用的参数:
vertical_strategy
:用于指定垂直方向上的表格线提取策略,可以是 “lines”、“text” 或 “mixed” 中的任意一种,默认值为 “lines”。horizontal_strategy
:用于指定水平方向上的表格线提取策略,可以是 “lines”、“text” 或 “mixed” 中的任意一种,默认值为 “lines”。snap_tolerance
:用于指定在表格提取过程中两个元素之间的距离阈值,如果它们之间的距离小于该值,则会被视为同一元素。默认值为 3。join_tolerance
:用于指定在表格提取过程中两个单元格相连时的距离阈值,如果它们之间的距离小于该值,则它们将被合并为同一个单元格。默认值为 2。edge_tolerance
:用于指定在表格提取过程中一个元素的边缘与页面边缘之间的距离阈值,如果它们之间的距离小于该值,则该元素将被忽略。默认值为 10。min_words
:用于指定一个单元格必须包含的最少文本块数目,默认值为 1。snap_x_tolerance
:用于在表格提取过程中校正列位置的参数,允许水平方向上的一些偏离。默认值为 None。snap_y_tolerance
:用于在表格提取过程中校正行位置的参数,允许垂直方向上的一些偏离。默认值为 None。intersection_x_tolerance
:用于调整表格列位置的参数,允许一些列交叉或合并。默认值为 None。
需要注意的是,不同的参数组合可能会产生不同的结果,具体使用时应根据实际情况进行调整。
extract_text 提取字符串,可选keep_blank_chars=True参数,保留空格字符串,在加上正则可以结构化信息
图像显示
im = page.to_image()
table_settings ={}
im.reset().debug_tablefinder(table_settings) #显示表格
安装imagemagick,强大且免费的命令行图片批量处理工具(尤其是pdf图片互相转换)
安装imagemagick https://imagemagick.org/script/download.php#windows
报错:wand.exceptions.DelegateError: FailedToExecuteCommand `“gswin64c.exe” ,缺少了对适量图 栅格化的软件,需要安装一个Ghostscript软件
https://blog.youkuaiyun.com/qq_44795036/article/details/125212424
下载ghostscript https://www.ghostscript.com/releases/gsdnld.html
实践
使用pdfplumber包转换excel,注意转换后pdf的换号符会保留。
通过extract_table方法
import pdfplumber
from openpyxl import Workbook
from tqdm import tqdm
def pdfplumber_extract_table():
'''
pdfplumber 是专门设计来提取 PDF 文档中的文本和表格数据的 Python 库。它提供了一种相对简单的方式来访问和提取 PDF 文件中的信息。pdfplumber 的一个突出特点是它对表格提取的支持,它可以识别表格结构并以结构化的形式提取数据。
pdfplumber 可能在处理非常复杂或不规则格式的 PDF 文件时遇到挑战。
Returns:
'''
total_df = pd.DataFrame([], columns=col_list)
# 打开pdf
with pdfplumber.open(pdf_file) as pdf:
for page in tqdm(pdf.pages):
# 提取表格信息
tabs = page.extract_tables()
# print(table)
# 格式化表格数据
for tab in tabs:
df = pd.DataFrame(tab[1:])
df['页数'] = str(page).split(':')[-1][:-1]
total_df = pd.concat([total_df, df.iloc[1:, :]], axis=0)
total_df.to_excel(result_file)