python - 如何在 Python 中从 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
有什么想法吗?
解决方案
经过一番挣扎,我找到了办法。
对于文件的每一页,有必要在 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))
推荐阅读
- mapbox - 我可以将 Azure Maps 磁贴用作 Mapbox 样式 JSON 文件的数据源吗?
- c++ - 编写内核配置时“不是目录”
- javascript - 如何用时间数据制作进度条?
- reactjs - 引入 ALB 后,发生混合内容错误
- asp.net - 如何在一个逗号分隔值中获取列值
- firebase - 消除阅读所有集合,只允许几个文件?
- google-analytics - Google Analytics Gtag 选项不报告综合浏览量
- asp.net-core - HttpClient GET 返回 404 未找到
- ios - SwiftUI:转换插入在 NavigationView 中不起作用
- javascript - 使用 v-for 和 v-bind:key