python?pdfplumber庫批量提取pdf表格數(shù)據(jù)轉(zhuǎn)換為excel
需求
想要提取 pdf 的數(shù)據(jù),保存到 excel 中。雖然是可以直接利用 WPS 將 pdf 文件輸出成 excel,但這個功能是收費的,而且如果將大量pdf轉(zhuǎn)excel的時候,手動去輸出是非常耗時的。我們可以利用 python 的三方工具庫 pdfplumber 快速完成這個功能。
一、實現(xiàn)效果圖
二、pdfplumber 庫
pdfplumber 是一個開源 python 工具庫-,可以方便地獲取 pdf 的各種信息,包括文本、表格、圖表、尺寸等。完成我們本文的需求,主要使用 pdfplumber 提取 pdf 表格數(shù)據(jù)。
安裝命令
pip install pdfplumber
三、代碼實現(xiàn)
1、導(dǎo)入相關(guān)包
import pdfplumber import pandas as pd
2、讀取 pdf , 并獲取 pdf 的頁數(shù)
pdf = pdfplumber.open("/Users/wangwangyuqing/Desktop/1.pdf") pages = pdf.pages
3、提取單個 pdf 文件,保存成 excel
if len(pages) > 1: tables = [] for each in pages: table = each.extract_table() tables.extend(table) else: tables = each.extract_table() data = pd.DataFrame(tables[1:], columns=tables[0]) data data.to_excel("/Users/wangwangyuqing/Desktop/1.xlsx", index=False)
4、提取文件夾下多個 pdf 文件,保存成 excel
import os import glob path = r'/Users/wangwangyuqing/Desktop/pdf文件' for f in glob.glob(os.path.join(path, "*.pdf")): res = save_pdf_to_excel(f) print(res) def save_pdf_to_excel(path): # print('文件名為:',path.split('/')[-1].split('.')[0] + '.xlsx') pdf = pdfplumber.open(path) pages = pdf.pages if len(pages) > 1: tables = [] for each in pages: table = each.extract_table() tables.extend(table) else: tables = each.extract_table() data = pd.DataFrame(tables[1:], columns=tables[0]) file_name = path.split('/')[-1].split('.')[0] + '.xlsx' data.to_excel("/Users/wangwangyuqing/Desktop/data/{}".format(file_name), index=False) return '保存成功!'
小結(jié)
python 中還有很多庫可以處理 pdf,比如 PyPDF2、pdfminer 等,本文選擇pdfplumber 的原因在于能輕松訪問有關(guān) PDF 的所有詳細信息,包括作者、來源、日期等,并且用于提取文本和表格的方法靈活可定制。大家可以根據(jù)手頭數(shù)據(jù)需求,再去解鎖 pdfplumber 的更多用法。
以上就是python pdfplumber庫批量提取pdf表格數(shù)據(jù)轉(zhuǎn)換為excel的詳細內(nèi)容,更多關(guān)于python pdfplumber庫pdf轉(zhuǎn)換excel的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python解析中國天氣網(wǎng)的天氣數(shù)據(jù)
最近學(xué)習(xí)python 感覺這門腳本語言十分靈活 而且功能十分強大 尤其是他re庫用于正則匹配十分強大,寫了個例子解析中國天氣網(wǎng)2014-03-03Python實現(xiàn)讀取目錄所有文件的文件名并保存到txt文件代碼
這篇文章主要介紹了Python實現(xiàn)讀取目錄所有文件的文件名并保存到txt文件代碼,本文分別使用os.listdir和os.walk實現(xiàn)給出兩段實現(xiàn)代碼,需要的朋友可以參考下2014-11-11python中關(guān)于property的最詳細使用方法
這篇文章主要介紹了python中關(guān)于property的最詳細使用方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04