背景:
在读取PDF上文字的时候,发现有些pdf是图片格式的,常规的pdf库是提取不到的。因此考虑使用OCR进行提取。
依赖:
安装 EasyOCR 和相关依赖
首先,您需要安装 EasyOCR
和 pdf2image
(用于将 PDF 转换为图像):
pip install easyocr pdf2image requests numpy
安装 poppler(如果尚未安装)
由于 pdf2image
依赖 poppler
来处理 PDF 文件,因此需要安装 poppler
。在 macOS 上,您可以使用 Homebrew 进行安装:
brew install poppler
在 Linux 系统上,您可以使用以下命令安装 poppler
:
sudo apt-get install poppler-utils
最终代码
import requests
from pdf2image import convert_from_path
import easyocr
import numpy as np
import tempfile
import os
def download_pdf(url, save_path):
response = requests.get(url)
with open(save_path, 'wb') as f:
f.write(response.content)
def ocr_pdf_using_easyocr(url):
# Step 1: Download the PDF
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as temp_pdf:
download_pdf(url, temp_pdf.name)
# Step 2: Convert PDF to images
images = convert_from_path(temp_pdf.name)
# Step 3: Initialize EasyOCR
reader = easyocr.Reader(['ch_sim', 'en']) # Simplified Chinese and English
# Step 4: Perform OCR on each image
all_text = []
for image in images:
# Convert PIL Image to numpy array
image_np = np.array(image)
result = reader.readtext(image_np)
for (bbox, text, prob) in result:
all_text.append(text)
# Clean up the temporary PDF file
os.remove(temp_pdf.name)
return "\n".join(all_text)
# Usage
url = "./0b3b9b0c0b594c2fb7ea28adb80c1163.pdf"
extracted_text = ocr_pdf_using_easyocr(url)
print(extracted_text)