天天看點

python程式設計:tabula、pdfplumber、camelot進行表格資料識别準備資料1、tabula2、pdfplumber3、camelot總結

本文就目前 python

圖表識别的庫進行測試

1、tabula

2、pdfplumber

3、camelot

準備資料

excel:names.xlsx,兩個表格

表格1:所有字段都被線條包圍

表格2:最外層沒有線條包圍

python程式設計:tabula、pdfplumber、camelot進行表格資料識别準備資料1、tabula2、pdfplumber3、camelot總結

将excel另存為pdf:names.pdf

python程式設計:tabula、pdfplumber、camelot進行表格資料識别準備資料1、tabula2、pdfplumber3、camelot總結

java項目:

https://github.com/tabulapdf

自帶可視化界面的pdf提取表格資料工具:

https://tabula.technology/

python接口:

https://github.com/chezou/tabula-py

安裝:

pip install tabula-py      

依賴:

Java 7, 8

代碼示例:

import tabula

tabula.convert_into(
    input_path="source/names.pdf",
    output_path="source/names.csv",
    output_format='csv'
)      

轉換出來的names.csv,發現隻有表格1被提取出來了,而且不規範,中間多了逗号

"姓名",年齡,性别
"李雷",,20 男
"韓梅梅",,23 女
"趙小三",,25 女
      

github:

https://github.com/jsvine/pdfplumber

安裝

pip install pdfplumber      
import pdfplumber
import pandas as pd

with pdfplumber.open("source/names.pdf") as pdf:
    # 擷取第一頁
    first_page = pdf.pages[0]
    
    # 解析文本
    text = first_page.extract_text()
    print(text)
    
    # 解析表格
    tables = first_page.extract_tables()
    for table in tables:
        print(table)
        # df = pd.DataFrame(table[1:], columns=table[0])
        for row in table:
            for cell in row:
                print(cell, end="\t|")
            print()
""" 
表格1:
姓名 年齡 性别
李雷 20 男
韓梅梅 23 女
趙小三 25 女

Table2:
Name Age Gender
Tom 30 Male
Jack 33 Male
Jone 31 Female

[['姓名', '年齡', '性别'], ['李雷', '20', '男'], ['韓梅梅', '23', '女'], ['趙小三', '25', '女']]

姓名  |年齡 |性别 |
李雷  |20 |男  |
韓梅梅 |23 |女  |
趙小三 |25 |女  |

[['30'], ['33']]

30  |
33  |

"""      

文本解析的很全,隻有表格1解析完全了,表格2隻是解析了有框的部分

https://github.com/socialcopsdev/camelot

安裝:

pip install camelot-py[cv]      

示例

import camelot

tables = camelot.read_pdf("source/names.pdf")
tables.export("source/names.csv")      

生成2個檔案:

source/names-page-1-table-1.csv

"姓名","年齡","性别"
"李雷","20 男",""
"韓梅梅","23 女",""
"趙小三","25 女",""
      

source/names-page-1-table-2.csv

"Name","Age","Gender"
"Tom","","30 Male"
"Jack","","33 Male"
"Jone","","31 Female"
      

發現表格2的内容被解析出來了,不過兩個表格的内容都錯位了

經過測試後,發現這3個庫對表格識别都不是太好

總結

庫名 說明
tabula 能提取完整表格,提取結果不規範
pdfplumber 能提取完整表格,提取結果較為規範
camelot 能提取完整表格和不完整表格,提取結果不規範