从 PDF 表格中获取数据是一项痛苦的工作。不久前,一位开发者提供了一个名为 Camelot 的工具,使用三行代码就能从 PDF 文件中提取表格数据。
项目地址:https://github.com/camelot-dev/camelot
项目作者提供了三种安装方法。首先,你可以使用 Conda 进行安装,这是最简单的。
conda install -c conda-forge camelot-py
最流行的安装方法是使用 pip 安装。
pip install camelot-py[cv]
还可以从项目中克隆代码,并使用源码安装。
git clone https://www.github.com/camelot-dev/camelot
cd camelot
pip install ".[cv]"
我选择用pip安装包,装好包后就来读取PDF文件了
import camelot
tables = camelot.read_pdf('1.pdf')
然后就报错了。。
然后安装ghostscript
依然报错
最后在这个贴子上了解决方法https://github.com/atlanhq/camelot/issues/282
需要在ghostscript官网下载exe文件安装,下载地址:https://www.ghostscript.com/download/gsdnld.html
安装后就不报错了
接着读取pdf,发现读取的表是空的,就去阅读了一下说明,发现如果不设置页面,默认读取第一页
然后找到PDF中表格对应的页面,再执行代码
效果还不错,然后我试了下另外一个PDF文档,又出现了问题。。 表格又是空的
对比了两个文档,发现pdf1中选中页中有两个表格,且是三线表,而pdf2中只有一个表格,还是传统的表格。在pdf1中发现有一页只有一个三线表,就试了下那一页,发现仍然不能读取,那么问题应该就是camelot只能读取表格中的数据,读取不了三线表中的数据。
如果想把读取表格中的数据保存下来,可以参考如下代码
>>> tables[0].df # get a pandas DataFrame!
>>> tables.export('foo.csv', f='csv', compress=True) # json, excel, html, sqlite,可指定输出格式
>>> tables[0].to_csv('foo.csv') # to_json, to_excel, to_html, to_sqlite, 导出数据为文件
>>> tables
<TableList n=1>
>>> tables[0]
<Table shape=(7, 7)> # 获得输出的格式
>>> tables[0].parsing_report
{
'accuracy': 99.02,
'whitespace': 12.24,
'order': 1,
'page': 1
}