要提取PDF中的文字,你可以使用Python中的PyPDF2庫或pdfminer庫。
首先,你需要安裝所需的庫。在命令行中運行以下命令來安裝PyPDF2庫:
pip install PyPDF2
或者,運行以下命令來安裝pdfminer庫:
pip install pdfminer.six
然后,你可以根據你選擇的庫使用以下示例代碼來提取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)
請注意,這些代碼示例假設你已經將PDF文件的路徑存儲在變量file_path
中。你需要將其替換為你實際的PDF文件路徑。