banner
andrewji8

Being towards death

Heed not to the tree-rustling and leaf-lashing rain, Why not stroll along, whistle and sing under its rein. Lighter and better suited than horses are straw sandals and a bamboo staff, Who's afraid? A palm-leaf plaited cape provides enough to misty weather in life sustain. A thorny spring breeze sobers up the spirit, I feel a slight chill, The setting sun over the mountain offers greetings still. Looking back over the bleak passage survived, The return in time Shall not be affected by windswept rain or shine.
telegram
twitter
github

Python-Camelot:使用三行程式碼提取 PDF 表格資料

PDF 文件是一種非常常用的文件格式,通常用於正式的電子版文件。它能夠很好的將不同的排版格式固定下來,形成版面清晰且美觀的展示效果。然而,對於想要從 PDF 中提取信息的人們來說,PDF 是個噩夢,尤其是表格。

image

大量的學術報告、論文、分析文章都使用 PDF 展示其中的表格數據,但是對於如果想要直接從表格中複製數據則會非常麻煩。不久前,有一位開發者提供了一個可從文字 PDF 中提取表格信息的工具 ——Camelot,能夠直接將大部分表格轉換為 Pandas 的 Dataframe。

項目地址:https://github.com/camelot-dev/camelot

Camelot 是什麼

據項目介紹稱,Camelot 是一個 Python 工具,用於將 PDF 文件中的表格數據提取出來。

具體而言,用戶可以像使用 Pandas 那樣打開 PDF 文件,然後利用這個工具提取表格數據,最後再指定輸出的形式(如 csv 文件)。

代碼示例

項目提供的 PDF 文件如圖所示,假設用戶需要提取這些文字之間的表格 2-1 中的信息。

image
使用 Camelot 提取表格數據的代碼如下:

>>> import camelot
>>> tables = camelot.read_pdf('foo.pdf') #類似於Pandas打開CSV文件的形式
>>> 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
}

以下為輸出的結果,對於合併的單元格,Camelot 在抽取後做了空行處理,這是一個穩妥的方法。

image

安裝方法

項目作者提供了三種安裝方法。首先,你可以使用 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]"

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。