單位的刷臉考勤機后臺系統(tǒng)做得比較差,只能導(dǎo)出每個部門的出勤統(tǒng)計表pdf,格式如下:
近期領(lǐng)導(dǎo)要看所有部門的考勤數(shù)據(jù),于是動手快速寫了個合并pdf并輸出csv文件的腳本。
安裝模塊
pypdf2,pdfplumber,前者用于合并,后者用于讀表格。
C:\>pip install pypdf2
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting pypdf2
? Using cached https://pypi.tuna.tsinghua.edu.cn/packages/8e/5e/c86a5643653825d3c913719e788e41386bee415c2b87b4f955432f2de6b2/pypdf2-3.0.1-py3-none-any.whl (232 kB)
Installing collected packages: pypdf2
Successfully installed pypdf2-3.0.1
C:\>pip install pdfplumber
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting pdfplumber
? Using cached https://pypi.tuna.tsinghua.edu.cn/packages/f8/d3/f58c2d5d86a585e438c6708f568eca79e7c4e6ee3d5210cf8b31d38cb021/pdfplumber-0.10.3-py3-none-any.whl (48 kB)
Requirement already satisfied: pdfminer.six==20221105 in d:\program files\python\lib\site-packages (from pdfplumber) (20221105)
Requirement already satisfied: Pillow>=9.1 in d:\program files\python\lib\site-packages (from pdfplumber) (10.2.0)
Requirement already satisfied: pypdfium2>=4.18.0 in d:\program files\python\lib\site-packages (from pdfplumber) (4.25.0)
Requirement already satisfied: charset-normalizer>=2.0.0 in d:\program files\python\lib\site-packages (from pdfminer.six==20221105->pdfplumber) (3.3.2)
Requirement already satisfied: cryptography>=36.0.0 in d:\program files\python\lib\site-packages (from pdfminer.six==20221105->pdfplumber) (41.0.7)
Requirement already satisfied: cffi>=1.12 in d:\program files\python\lib\site-packages (from cryptography>=36.0.0->pdfminer.six==20221105->pdfplumber) (1.16.0)
Requirement already satisfied: pycparser in d:\program files\python\lib\site-packages (from cffi>=1.12->cryptography>=36.0.0->pdfminer.six==20221105->pdfplumber) (2.21)
Installing collected packages: pdfplumber
Successfully installed pdfplumber-0.10.3
讀取、合并文件
PyPDF2
PyPDF2 用于對PDF文件的分離、合并、裁剪、轉(zhuǎn)換、加密、解密等操作。
讀取和合并pdf文件正好以前寫過,主要代碼如下:?
? ? with codecs.open(file_path, 'rb', encoding='utf-16') as file:
? ? ? ? pdf_reader = PyPDF2.PdfReader(file)
? ? ? ? text = ''
? ? ? ? for page_num in range(len(pdf_reader.pages)):
? ? ? ? ? ? tt = pdf_reader.pages[page_num].extract_text()
? ? ? ? ? ? print(tt)
? ? ? ? ? ? text += tt
......
? ? pdfMerge = PyPDF2.PdfMerger()
? ? try:
? ? ? ? for pdf in pdfLists:
? ? ? ? ? ? pdfMerge.append(pdf, import_outline=False)
? ? ? ? pdfMerge.write(pdfFileN)
? ? ? ? pdfMerge.close
? ? ? ? print("PDF files merged successfully!")
......
表格讀取
pdfplumber
pdfplumber 用于讀取PDF文件文本和表格提取,功能比較均衡。
優(yōu)點:
- 每頁單獨對象,支持文本、表格數(shù)據(jù)的抽?。咙c)
- 文本抽取:保留了文本的格式,比如換行位置有空格,可以通過這個特點將一段的文本整合
- 表格數(shù)據(jù)抽?。翰粫粨Q行數(shù)據(jù)所干擾
缺點:
- 進行文本抽取時,如果一頁有文本和表格,那么抽取的文本數(shù)據(jù)也會包括表格數(shù)據(jù)
- 對于有合并單元格的表格,無法還原表格結(jié)構(gòu)
- 表格數(shù)據(jù)不能100%保證和原數(shù)據(jù)一致,可能缺少幾個字,可能識別出錯等
- 對于無邊框的表格,處理效果很差
- 流程圖和時序圖會對處理產(chǎn)生嚴重影響
讀取代碼如下:
pdf = ?pdfplumber.open(pdfFileN)
for page in pdf.pages:
? ? tables = page.extract_tables(table_settings = {})
? ? for table in tables:
? ? ? ? print(table)
遍歷得到的是一個個二維列表,可以根據(jù)需要自己清洗數(shù)據(jù)。
程序界面
easygui
就用這個庫,弄2個對話框簡單了事:
選擇一個文件夾,把其下的所有pdf文件合并,然后轉(zhuǎn)換輸出csv文件:?
輸出的文件格式如下:
更多easygui內(nèi)容請見:?
Python 簡易圖形界面庫easygui 對話框大全-CSDN博客文章瀏覽閱讀4.2k次,點贊117次,收藏96次。提供了“繼續(xù)”和“取消”選項,并返回True(表示繼續(xù))或False(表示取消)。", title="結(jié)束", ok_button="干得好!easygui.ccbox(msg, title, choices=('退出[E]','取消[C]'))選擇“Chocolate”后點OK就把所選擇的項賦值給變量choice,點Cancel則返回None。如果選擇了第一個按鈕,則返回“True”。提供了Yes和No的選擇,并返回“True”或“False”。在列表框中提供了可供選擇的由元組或列表指定的選項列表。https://blog.csdn.net/boysoft2002/article/details/135179267Python 簡易圖形界面庫easygui 對話框大全(續(xù))-CSDN博客文章瀏覽閱讀1.2k次,點贊67次,收藏58次。Python 簡易圖形界面庫easygui 對話框大全-CSDN博客提供了“繼續(xù)”和“取消”選項,并返回True(表示繼續(xù))或False(表示取消)。", title="結(jié)束", ok_button="干得好!easygui.ccbox(msg, title, choices=('退出[E]','取消[C]'))選擇“Chocolate”后點OK就把所選擇的項賦值給變量choice,點Cancel則返回None。如果選擇了第一個按鈕,則返回“True”。https://blog.csdn.net/boysoft2002/article/details/135297373以上幾樣庫拼湊在一起,就可以完成合并和轉(zhuǎn)換pdf表格,完整代碼如下:
import sys,os
import datetime as dt
import PyPDF2,pdfplumber
import easygui as eg
def get_pdf_text(file_path):
with codecs.open(file_path, 'rb', encoding='utf-16') as file:
pdf_reader = PyPDF2.PdfReader(file)
text = ''
for page_num in range(len(pdf_reader.pages)):
tt = pdf_reader.pages[page_num].extract_text()
print(tt)
text += tt
return text
def strDateTime(diff=0):
now = dt.datetime.now()
future_time = now + dt.timedelta(days=diff)
return f'{future_time.year:04}{future_time.month:02}{future_time.day:02}_{future_time.hour:02}{future_time.minute:02}{future_time.second:02}'
txtStart = "PDFmerged_"
try:
Dir = eg.diropenbox(msg=None, title=None, default='./')
pdfLists = [f for f in os.listdir(Dir) if f.endswith('.pdf') and not f.startswith(txtStart)]
pdfFileN = Dir + '\\' + txtStart + strDateTime() + ".pdf"
except:
print('取消退出!')
sys.exit(0)
if len(pdfLists)==0:
eg.msgbox("此文件夾沒有Pdf文件!", title="結(jié)束", ok_button="Fail")
sys.exit(0)
else:
pdfMerge = PyPDF2.PdfMerger()
try:
for pdf in pdfLists:
pdfMerge.append(pdf, import_outline=False)
pdfMerge.write(pdfFileN)
pdfMerge.close
print("PDF files merged successfully!")
except:
eg.msgbox("合并pdf失??!", title="結(jié)束", ok_button="Fail")
sys.exit(0)
pdf = pdfplumber.open(pdfFileN)
dct = dict()
for page in pdf.pages:
tables = page.extract_tables(table_settings = {})
for table in tables:
for lst in table:
tmp = lst[1:]
tmp = [tmp[0]]+tmp[3:8]+[tmp[-1]]
try:
tmp[0] = tmp[0].replace('\n','')
tmp[0] = tmp[0].split('/')
tmp[0] = tmp[0][-1]
except:
pass
if lst[0]=='時間':
dct[lst[0]] = tmp[0]
else:
dct[','.join([lst[0],tmp[0] if tmp[0] else ''])] = ','.join(tmp[1:]) if all(tmp[1:]) else ''
pdf.close()
try:os.remove(pdfFileN)
except:pass
try:
fn = "考勤表(" + dct['時間'] + ")"+strDateTime()+".csv"
except:
fn = "考勤表"+strDateTime()+".csv"
try:
with open(fn, 'w') as f:
for k,v in dct.items():
print(','.join([k,v]), file=f)
eg.msgbox(f"考勤表保存成功!\n\n\n\t文件名:{fn}", title="結(jié)束", ok_button="Good!")
print(f"CSV file written successfully! by HannYang {strDateTime()}")
except:
eg.msgbox("保存csv文件失敗!", title="結(jié)束", ok_button="Fail")
后話
如果要直接輸出Excel表格,則需要另安裝和導(dǎo)入xlwt模塊。實現(xiàn)的代碼大致如下:
? ? myxl = xlwt.Workbook()
? ? style = xlwt.easyxf('align: wrap yes; align: horiz center; font: bold yes;borders:top thin; borders:bottom thin; borders:left thin; borders:right thin;')?
? ? sheet = myxl.add_sheet('考勤表')
? ? wcol = [20,40,50,75,40,75]
? ? for i in range(6):
? ? ? ? sheet.col(i).width = wcol[i]*80
? ? sheet.write_merge(0,0,0,8,'出勤統(tǒng)計報表',style)
? ? style = xlwt.easyxf('borders:top thin; borders:bottom thin; borders:left thin; borders:right thin;')?
? ? sheet.write_merge(1,1,0,1,'單位(蓋章):',style)
? ? sheet.write_merge(2,2,0,1,'*經(jīng)辦人:',style)
? ? sheet.write(1,3,'填表日期:',style)
? ? sheet.write_merge(1,1,4,8,strToday(),style)
? ? sheet.write(2,3,'*聯(lián)系電話:',style)
? ? sheet.write(2,2,adminName,style)
? ? sheet.write_merge(2,2,4,8,adminMobil,style)
? ? for i,t in enumerate(head.strip().split(',')):
? ? ? ? ? ? sheet.write(3,i,t,style)
? ? with open('考勤表.csv', 'r') as f:
? ? ? ? for i,row in enumerate(csv.reader(f)):
? ? ? ? ? ? if i==0:continue
? ? ? ? ? ? for j,col in enumerate(row):
? ? ? ? ? ? ? ? ? ? sheet.write(3+i,j,col,style)
? ? excelfile = 'Output_'+strDateTime()+'('+defaultValue+').xls'
? ? myxl.save(excelfile)
另外不趕時間的話,還可以用PySimpleGUI庫寫個帶漂亮gui界面的程序,具體操作方法請參見:
探索PySimpleGUI:一款簡潔易用的圖形用戶界面庫-CSDN博客文章瀏覽閱讀1.9k次,點贊105次,收藏88次。PySimpleGUI是一個基于Tkinter、WxPython、Qt等底層庫構(gòu)建的圖形界面框架,其設(shè)計目標(biāo)是使Python GUI編程變得更加簡單直觀,大大降低了入門門檻。無論是初學(xué)者還是經(jīng)驗豐富的開發(fā)者,都可以快速上手并高效地創(chuàng)建出功能豐富、外觀現(xiàn)代的桌面應(yīng)用程序。PySimpleGUI的核心優(yōu)勢在于其高度抽象化的API設(shè)計,它提供了包括按鈕、輸入框、列表框、滑塊等各種常見的GUI元素。除了基本的布局和樣式設(shè)置,PySimpleGUI還支持事件驅(qū)動的編程模型。https://blog.csdn.net/boysoft2002/article/details/135315323
目錄
安裝模塊
讀取、合并文件
PyPDF2
表格讀取
pdfplumber
程序界面
easygui文章來源:http://www.zghlxwxcb.cn/news/detail-777775.html
后話文章來源地址http://www.zghlxwxcb.cn/news/detail-777775.html
到了這里,關(guān)于Python 快速合并PDF表格轉(zhuǎn)換輸出CSV文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!