如何在 PDF 文件中查找表格网格线?

问题描述

为了更准确地提取表格单元格中嵌入的类似表格的数据,我希望能够像这样识别 PDF 中的表格单元格边界:

pdf table example

我曾尝试使用 Camelot、pdfplumber 和 PyMuPDF 提取此类表格,并取得了不同程度的成功。但由于我们收到的 PDF 不一致,即使指定了表格边界,我也无法可靠地获得准确的结果。

我发现如果我通过明确指定单元格边界来单独提取每个表格单元格,结果会更好。我已经通过手动输入边界对此进行了测试,这是我使用 Camelot 的可视化调试工具获得的。

我的挑战是如何以编程方式识别表格单元格边界,因为表格可能从页面的任何位置开始,并且单元格的垂直高度可变。

在我看来,可以通过找到行分隔线的坐标来做到这一点,这对人类来说非常明显。但是我还没有弄清楚如何使用 python 工具找到这些行。这是可能的,还是有其他/更好的方法解决这个问题?

解决方法

我最近有一个类似的用例,我需要通过代码本身找出边界。对于您的用例,有两个选项:

  1. 如果要识别整个表的边界,可以执行以下操作:
import pdfplumber
pdf = pdfplumber.open('file_name.pdf')
p0 = pdf.pages[req_page] # go to the required page

tables = p0.debug_tablefinder() # list of tables which pdfplumber identifies
req_table = tables.tables[i] # Suppose you want to use ith table

req_table.bbox # gives you the bounding box of the table (coordinates)
  1. 您想访问表格中的每个单元格并从中提取单词,例如:
import pdfplumber
pdf = pdfplumber.open('file_name.pdf')
p0 = pdf.pages[req_page] # go to the required page

tables = p0.debug_tablefinder() # list of tables which pdfplumber identifies
req_table = tables.tables[i] # Suppose you want to use ith table

cells = req_table.cells # gives list of all cells in that table

for cell in cells[i:j]: # iterating through the required cells
    p0.crop(cell).extract_words() # extract the words 

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...