用 Python 閱讀 PDF
    
    
            Samyak Jain
    2023年1月30日
    
    Python
    Python PDF
    
- 
          
            在 Python 中使用 PyPDF2模組閱讀 PDF
- 
          
            在 Python 中使用 PDFplumber模組閱讀 PDF
- 
          
            在 Python 中使用 textract模組閱讀 PDF
- 
          
            在 Python 中使用 PDFminer.six模組閱讀 PDF
 
PDF 文件無法修改,但可以輕鬆可靠地共享。PDF 文件中可以有不同的元素,如文字、連結、影象、表格、表單等。
在本教程中,我們將使用 Python 讀取 PDF 檔案。
在 Python 中使用 PyPDF2 模組閱讀 PDF
PyPDF2 是一個 Python 模組,我們可以使用它來提取 PDF 文件的資訊、合併文件、拆分文件、裁剪頁面、加密或解密 PDF 檔案等等。
我們使用 open('document_path.PDF', 'rb') 以讀取二進位制模式開啟 PDF 文件。PDFFileReader() 用於建立一個 PDF 閱讀器物件來閱讀文件。我們可以使用 getPage() 和 extractText() 方法從 PDF 文件的頁面中提取文字。要獲取給定 PDF 文件中的頁數,我們使用 .numPages。
例如,
from PyPDF2 import PDFFileReader
temp = open("document_path.PDF", "rb")
PDF_read = PDFFileReader(temp)
first_page = PDF_read.getPage(0)
print(first_page.extractText())
上面的程式碼將在提供的 PDF 文件的第一頁上列印文字。
在 Python 中使用 PDFplumber 模組閱讀 PDF
PDFplumber 是一個 Python 模組,我們可以使用它從 PDF 文件和其他內容中讀取和提取文字。與 PyPDF2 模組相比,PDFplumber 模組更有效。這裡我們還使用了 open() 函式來讀取 PDF 檔案。
例如,
import PDFplumber
with PDFplumber.open("document_path.PDF") as temp:
    first_page = temp.pages[0]
    print(first_page.extract_text())
上面的程式碼將從提供的 PDF 文件的第一頁列印文字。
在 Python 中使用 textract 模組閱讀 PDF
我們可以使用 textract 模組中的函式 textract.process() 來讀取 PDF 文件。
例如,
import textract
PDF_read = textract.process("document_path.PDF", method="PDFminer")
在 Python 中使用 PDFminer.six 模組閱讀 PDF
PDFminer.six 是一個 Python 模組,我們可以使用它從 PDF 文件中讀取和提取文字。我們將使用該模組中的 extract_text() 函式來讀取 PDF 中的文字。
例如,
from PDFminer.high_level import extract_text
PDF_read = extract_text("document_path.PDF")
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe