首页 > 解决方案 > 如何在 Python 中从 PDF 中提取表格?

问题描述

我有数千个 PDF 文件,仅由表格组成,具有以下结构:

pdf文件

但是,尽管结构相当结构化,但我无法在不丢失结构的情况下阅读表格。

我尝试了 PyPDF2,但数据完全搞砸了。

import PyPDF2 

pdfFileObj = open(pdf_file.pdf, 'rb') 
pdfReader = PyPDF2.PdfFileReader(pdfFileObj) 
pageObj = pdfReader.getPage(0) 

print(pageObj.extractText())
print(pageObj.extractText().split('\n')[0]) 
print(pageObj.extractText().split('/')[0]) 

我也试过 Tabula,但它只读取标题(而不是表格的内容)

from tabula import read_pdf

pdfFile1 = read_pdf(pdf_file.pdf, output_format = 'json') #Option 1: reads all the headers
pdfFile2 = read_pdf(pdf_file.pdf, multiple_tables = True) #Option 2: reads only the first header and few lines of content

有什么想法吗?

标签: pythonpdf

解决方案


经过一番挣扎,我找到了办法。

对于文件的每一页,有必要在 tabula 的 read_pdf 函数中定义表格的区域和列的限制。

这是工作代码

import PyPDF2 
from tabula import read_pdf

# Get the number of pages in the file
pdfFileObj = open(pdf_file, 'rb') 
pdfReader = PyPDF2.PdfFileReader(pdfFileObj) 
n_pages = pdfReader.getNumPages()

# For each page the table can be read with the following code
table_pdf = read_pdf(pdf_file, guess=False, pages = 1, stream=True , encoding="utf-8", area = (96,24,558,750), columns = (24,127,220,274,298,325,343,364,459,545,591,748))

推荐阅读