python - 如何在 PDF 文件中查找表格网格线?
问题描述
为了更准确地提取嵌入在表格单元格中的类似表格的数据,我希望能够识别 PDF 中的表格单元格边界,如下所示:
我曾尝试使用 Camelot、pdfplumber 和 PyMuPDF 提取此类表,并取得了不同程度的成功。但由于我们收到的 PDF 不一致,即使指定表格边界,我也无法可靠地获得准确的结果。
我发现如果我通过明确指定单元格边界来单独提取每个表格单元格,结果会更好。我已经通过手动输入边界进行了测试,这是我使用 Camelot 的可视化调试工具获得的。
我的挑战是如何以编程方式识别表格单元格边界,因为表格可能从页面上的任何位置开始,并且单元格的垂直高度可变。
在我看来,可以通过查找行分隔线的坐标来做到这一点,这对人类来说在视觉上是如此明显。但我还没有弄清楚如何使用 python 工具找到这些行。这是可能的,还是有其他/更好的方法来解决这个问题?
解决方案
我最近有一个类似的用例,我需要通过代码本身找出边界。对于您的用例,有两种选择:
- 如果要识别整个表的边界,可以执行以下操作:
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)
- 您想访问表格中的每个单元格并从中提取单词:
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
推荐阅读
- android - 如何在同一布局中创建指向元素的链接?
- azure-devops - 无法将同一集合两次导入 Azure DevOps Services
- electron - npm run make 在电子锻造中不起作用
- git - 远程:在 /home/kovair/git_home/OmnibusAdapterListener/Log4perl/lib/Log/Log4perl/Appender.pm 第 164 行的连接或字符串中使用未初始化的值
- android - 有没有办法在幕后工作以防止 ANR 在 Android 中长时间工作?
- javascript - 加速脚本 Gscript
- c++ - 为什么此 cin 验证不适用于其他文件,而仅适用于一个文件?
- angularjs - Echarts 3.6.2 图例类型“滚动”未正确应用
- authentication - 使用 Auth0 对 cypress 进行身份验证
- c++ - 在其构造函数中调用类对象的全局实例