在處理大型PDF文件時,將它們分解成更小、更易于管理的塊通常是有益的。這個過程稱為分區,它可以提高處理效率,并使分析或操作文檔變得更容易。在本文中,我們將討論如何使用Python和為Unstructured.io庫將PDF文件劃分為更小的部分。
我們將使用兩個Python庫來完成此任務:
- PyPDF2:一個可以讀、寫、合并和分割PDF文件的庫。
- Unstructured.io:一個可以使用文檔圖像分析模型分割PDF文檔的庫。
下面是完成這個任務的Python代碼:
from PyPDF2 import PdfReader, PdfWriter
from unstructured.partition.pdf import partition_pdfimport os
from os import path# Create the output directory if it doesn't exist
# os.makedirs('./output', exist_ok=True)
path = path.abspath(path.dirname(__file__))# pdf_file = path + '/sample01.pdf'filename = path + "/sample02.pdf"# Read the original PDF
input_pdf = PdfReader(f'{filename}')batch_size = 2
num_batches = len(input_pdf.pages) // batch_size + 1filename = path + "/output"
# Extract batches of 100 pages from the PDF
for b in range(num_batches):writer = PdfWriter()# Get the start and end page numbers for this batchstart_page = b * batch_sizeend_page = min((b+1) * batch_size, len(input_pdf.pages))# Add pages in this batch to the writerfor i in range(start_page, end_page):writer.add_page(input_pdf.pages[i])# Save the batch to a separate PDF filebatch_filename = f'{filename}-batch{b+1}.pdf'with open(batch_filename, 'wb') as output_file:writer.write(output_file)# Now you can use the `partition_pdf` function from Unstructured.io to analyze the batchelements = partition_pdf(filename=batch_filename)print(elements)# Do something with `elements`...# This will process without issue# 抽取表格數據elements = partition_pdf("copy-protected.pdf", strategy="hi_res")
第一步:讀PDF文件
首先,我們從PyPDF2庫導入必要的類:PdfReader和PdfWriter。PdfReader類用于讀取原始PDF文件,該文件存儲在名為“exam-prep”的子目錄中。
步驟2:分區PDF
我們決定批大小,即PDF的每個塊將包含的頁數。在本例中,我們選擇了100頁的批處理大小,但這可以根據您的需要進行調整。
然后通過將PDF中的總頁數除以批大小來計算批數量。添加1以確保在頁面總數不是批大小的倍數時捕獲所有剩余頁面。
步驟3:寫PDF塊
接下來,循環遍歷每個批處理,為每個批處理創建一個新的PdfWriter對象。對于每個批處理,我們計算起始頁碼和結束頁碼,并使用add_page方法將該范圍內的每個頁碼添加到PdfWriter。
一旦添加了批處理的所有頁面,我們將它們寫入‘output’子目錄下的新PDF文件中。每個塊的文件名包括原始文件名和批號。
步驟4:分析PDF塊
將PDF分成更小的塊后,現在可以使用來自非結構化的partition_pdf函數。IO庫來分析每個批處理。該函數使用文檔圖像分析模型對PDF文檔進行分段,并返回已解析PDF文檔頁面中出現的元素列表。
最后總結
將大型PDF文件劃分為更小的塊可以使它們更容易、容錯和消耗更少的內存。