You need to enable JavaScript to run this app. 如何使用pdfplumber提取PDF无可见竖线表格为规范行列数据
优惠活动
大模型
产品
解决方案
定价
更多

如何使用pdfplumber提取PDF无可见竖线表格为规范行列数据

无可见垂直分隔线PDF表格提取解决方案

pdfplumber默认表格提取策略依赖可见边框线识别列边界,无垂直分隔线时会默认将整行识别为单列,可通过以下两种方案解决:

方案1:显式指定垂直分割线(推荐,准确率最高)

首先运行以下代码获取页面字符的x坐标分布,确认列分界位置:

import pdfplumber
with pdfplumber.open('test.pdf') as pdf:
    page = pdf.pages[0]
    # 打印字符文本与对应的左x坐标,用于统计列边界
    for char in page.chars:
        print(f"文本:{char['text']},x坐标:{char['x0']}")

根据x坐标的聚类分布整理出列分界的x值列表,将参数传入extract_tables的配置项:

import pdfplumber
import pandas as pd

with pdfplumber.open('test.pdf') as pdf:
    page = pdf.pages[0]
    tables = page.extract_tables(table_settings={
        # 显式指定垂直分割线策略
        "vertical_strategy": "explicit",
        # 替换为实际统计得到的列分界x坐标
        "vertical_lines": [90, 180, 270, 360, 450],
        # 按文本y坐标自动识别行边界,适配13行提取需求
        "horizontal_strategy": "text",
        # 调整行识别容差,避免同一行文本被拆分
        "snap_y_tolerance": 3
    })

# 输出验证结果
df = pd.DataFrame(tables[0])
print(df)
print(f"实际提取行数:{len(df)}")

方案2:整行提取后按规则拆分

如果表格列之间的间距有固定规律,可先提取整行文本再拆分:

import pdfplumber
import pandas as pd

with pdfplumber.open('test.pdf') as pdf:
    page = pdf.pages[0]
    # 按行提取页面纯文本
    lines = page.extract_text_simple().split('\n')
    table_data = []
    for line in lines:
        if not line.strip():
            continue
        # 可根据实际规则调整拆分逻辑,比如按固定宽度、多空格分隔等
        cols = [c.strip() for c in line.split() if c.strip()]
        table_data.append(cols)

df = pd.DataFrame(table_data)
print(df)

注意事项

  • 存在合并单元格的场景,提取后需要单独补全合并单元格的内容
  • snap_y_tolerance参数可根据实际行间距调整,数值越大越容易将相邻行合并,数值越小越容易拆分为多行
  • 垂直分割线的x值也可以通过pdf阅读器的坐标测量工具直接获取,无需运行字符统计代码

内容的提问来源于stack exchange,提问作者walter_anderson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 18:33:00