python作為一種具有相對簡單語法的高級解釋語言,即使對於那些沒有編程經驗的人來說,Python也是簡單易操作的。強大的Python庫讓你事半功倍。

在處理文本信息時,通常我們需要從word、PDF文檔中提取出信息,而PDF是最重要和最廣泛使用的用來呈現和交換文件的數字媒體之一,。PDF包含有用的信息,鏈接和按鈕,表單域,音頻,視頻和業務邏輯。python庫很好地集成並提供處理非結構化數據源。運用python可以輕鬆從PDF中提取有用信息後,您可以輕鬆地將該數據用於任何機器學習或自然語言處理模型。

常見的Python庫

以下是可用於處理PDF文件的一些Python庫

  1. PDFMiner :一個從PDF文檔中提取信息的工具。與其他PDF相關工具不同,它完全專註於獲取和分析文本數據。
  2. PyPDF2 :一個純python PDF庫,能夠分割,合併,裁剪和轉換PDF文件的頁面。它還可以向PDF文件添加自定義數據,查看選項和密碼。它可以從PDF中檢索文本和元數據,以及將整個文件合併在一起。
  3. Tabula-py:一個 tabula-java的簡單Python包裝器,它可以讀取PDF表。您可以從PDF讀取表格並轉換為pandas的DataFrame。tabula-py還允許您將PDF文件轉換為CSV / TSV / JSON文件。
  4. Slate:PDFMiner的包裝器實現
  5. PDFQuery:pdfminer,lxml和pyquery的輕量級包裝器。它旨在使用儘可能少的代碼可靠地從PDF集合中提取數據。
  6. xpdf :xpdf的 Python包裝器(目前只是「pdftotext」實用程序)

從pdf中提取文本

使用PyPDF2從pdf中提取簡單文本,示例代碼如下:

import PyPDF2
# pdf file object
# you can find find the pdf file with complete code in below
pdfFileObj = open(example.pdf, rb)
# pdf reader object
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
# number of pages in pdf
print(pdfReader.numPages)
# a page object
pageObj = pdfReader.getPage(0)
# extracting text from page.
# this will print the text you can also save that into String
print(pageObj.extractText())

從pdf中讀取表格數據

使用Pdf中的Table數據,我們可以使用Tabula-py,示例代碼如下:

import tabula
# readinf the PDF file that contain Table Data
# you can find find the pdf file with complete code in below
# read_pdf will save the pdf table into Pandas Dataframe
df = tabula.read_pdf("offense.pdf")
# in order to print first 5 lines of Table
df.head()

如果您的Pdf文件包含多個表,可以進行如下設置:

df = tabula.read_pdf(「crime.pdf」,multiple_tables = True)

還可以從任何特定PDF頁面的特定部分提取信息

tabula.read_pdf(「crime.pdf」,area =(126,149,212,462),pages = 1)

設置讀取輸出為JSON格式

tabula.read_pdf(「crime.pdf」,output_format =「json」)

將Pdf導出到Excel

使用以下代碼將PDF數據轉換為Excel或CSV

tabula.convert_into(「crime.pdf」,「crime_testing.xlsx」,output_format =「xlsx」)

更多參考資料

python提取pdf信息:

Working with PDF files in Python - GeeksforGeeks?

www.geeksforgeeks.org
圖標

原文:

https://towardsdatascience.com/python-for-pdf-ef0fac2808b0?

towardsdatascience.com

PyPDF2庫文檔:

Automate the Boring Stuff with Python?

automatetheboringstuff.com圖標

公眾號:深度學習與Python,專註於深度學習、機器學習前沿知識與資訊

推薦閱讀:

相关文章