溫馨提示×

python怎么提取pdf中的文字

小億
130
2023-12-21 16:11:49
欄目: 編程語言

要提取PDF中的文字,你可以使用Python中的PyPDF2庫或pdfminer庫。

首先,你需要安裝所需的庫。在命令行中運(yùn)行以下命令來安裝PyPDF2庫:

pip install PyPDF2

或者,運(yùn)行以下命令來安裝pdfminer庫:

pip install pdfminer.six

然后,你可以根據(jù)你選擇的庫使用以下示例代碼來提取PDF中的文字。

使用PyPDF2庫的示例代碼:

import PyPDF2

def extract_text_from_pdf(file_path):
    text = ""
    with open(file_path, "rb") as file:
        pdf = PyPDF2.PdfFileReader(file)
        num_pages = pdf.numPages
        for page in range(num_pages):
            page_obj = pdf.getPage(page)
            text += page_obj.extract_text()
    return text

file_path = "path_to_your_pdf_file"
text = extract_text_from_pdf(file_path)
print(text)

使用pdfminer庫的示例代碼:

import io
from pdfminer.converter import TextConverter
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfpage import PDFPage

def extract_text_from_pdf(file_path):
    text = ""
    with open(file_path, "rb") as file:
        resource_manager = PDFResourceManager()
        string_io = io.StringIO()
        converter = TextConverter(resource_manager, string_io)
        page_interpreter = PDFPageInterpreter(resource_manager, converter)
        for page in PDFPage.get_pages(file):
            page_interpreter.process_page(page)
        text = string_io.getvalue()
        converter.close()
        string_io.close()
    return text

file_path = "path_to_your_pdf_file"
text = extract_text_from_pdf(file_path)
print(text)

請注意,這些代碼示例假設(shè)你已經(jīng)將PDF文件的路徑存儲在變量file_path中。你需要將其替換為你實(shí)際的PDF文件路徑。

0