在Python中如何优雅地处理PDF文件
1. 引言
PDF文檔是我們在日常工作中經常會遇到的文件格式,有時我們需要編輯并從中提取一些有用的數據。在本文中,我將向大家介紹如何使用Python中的PDF庫從PDF文檔中提取文本、表格和圖像以及其他類型的數據。
 閑話少說,我們直接開始吧!
2. 從PDF文件中獲取文本
在Python中有多種庫可以幫助我們方便的從PDF文件中獲取對應的文本,其中最為常用的是PyPdf2,我們不妨來舉個栗子來看看相應的函數的使用方法。
樣例代碼如下:
# importing module import PyPDF2# create a pdf file object pdfFileObj = open('file.pdf', 'rb')# create a pdf reader object pdfReader = PyPDF2.PdfFileReader(pdfFileObj)# creating a page object pageObj = pdfReader.getPage(0)# extracte text from page print(pageObj.extractText())# closing the pdf file object pdfFileObj.close()在上述代碼中,我們逐行來分析:
- 首先我們導入我們的第三方庫PyPDF2
- 接著我們使用函數open()以二進制方式讀入我們的PDF文件
- 將讀入的文件對象傳遞給PdfFileReader函數
- 獲取PDF某個頁面的對象,生成pageObj
- 使用函數extractText()來提取文本信息
- 最后我們使用close函數來將PdfFileObj關閉
最終,關閉文件是必須的。如果我們讓它保持打開狀態,并試圖讀取另一個文件,此時它會給我們提示一個文件讀取的錯誤。
 上述代碼展示了提取單個頁面的邏輯,進而我們可以使用循環語句來讀取所有的頁面,樣例代碼如下:
舉例,假設我們需要的PDF文件如下:
則上述代碼的運行結果如下:
A Simple PDF File This is a small demonstration .pdf file - just for use in the Virtual Mechanics tutorials. More text. And more text. And more text. And more text. And more text. And more text. And more text. And more text. And more text. And more text. And more text. Boring, zzzzz. And more text. And more text. And more text. And more text. And more text. And more text. And more text. And more text. And more text. And more text. And more text. And more text. And more text. And more text. And more text. And more text. Even more. Continued on page 2 ...3. 從PDF文件中獲取表格
使用PyPDF2提取表不太方便,為了正確地從PDF文件中提取表格,我們需要采用計算機視覺的方法首先檢測這些表格,然后進行機器學習計算,最后在將其提取出來。
為了完成這項任務,這里推薦一個第三方python模塊,叫做Tabula,該模塊專門用于從pdf中讀取和提取表格,并以CSV格式存儲。
樣例代碼如下:
import tabula# Read pdf into list of DataFrame df = tabula.read_pdf("test.pdf", pages='all') print(df)上述代碼的解析如下:
- 首先我們引入我們所需的第三方庫tabula
- 接著我們使用函數read_pdf來讀取pdf文件,并提取所有頁面中的表格
- 最后我們使用打印函數將提取到的表格進行打印
當然,我們也可以將提取得到的數據以csv的方式進行存儲,樣例代碼如下:
import tabula# convert PDF into CSV file tabula.convert_into("test.pdf", "output.csv", output_format="csv", pages='all')4. 從PDF文件中獲取圖片
在Python中為了從PDF文件中提取圖像,我們必須使用其他第三方模塊。
安裝我們所需的第三方庫PyMuPDF以及圖像處理庫Pillow,安裝代碼如下:
pip install PyMuPDF Pillow從PDF文件中提取圖片的示例代碼如下:
import fitz import io from PIL import Imagepdf_file = fitz.open("test2.pdf") # iterate over PDF pagesfor page_index in range(len(pdf_file)):# get the page itselfpage = pdf_file[page_index]image_list = page.getImageList()for image_index, img in enumerate(page.getImageList(), start=1):# get the XREF of the imagexref = img[0]# extract the image bytesbase_image = pdf_file.extractImage(xref)image_bytes = base_image["image"]# get the image extensionimage_ext = base_image["ext"]# load it to PILimage = Image.open(io.BytesIO(image_bytes))# save itimage.save(open(f"image{page_index+1}_{image_index}.{image_ext}", "wb"))假設我們的PDF文件內容如下:
 
我們測試上述代碼,得到結果如下:
5. 總結
本文重點介紹了在Python中如何利用功能強大的第三方庫來從PDF文件中獲取文本表格和圖像數據,并給出了相應的代碼示例!
您學廢了嗎?
 關注公眾號《AI算法之道》,獲取更多AI算法資訊。
總結
以上是生活随笔為你收集整理的在Python中如何优雅地处理PDF文件的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: MicroSIP编译完全手册
- 下一篇: 目标检测M2Det论文总结
