如果你已经在本地安装了 tesseract
,但需要手动指定 tesseract
的路径,以下是正确的代码示例。你需要将 tesseract_cmd
设置为 tesseract
可执行文件的完整路径。
正确代码
from pdf2image import convert_from_path
import pytesseract
import os
# 设置 tesseract 的路径
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' # 替换为你的 tesseract 路径
def pdf_to_images(pdf_path, output_folder):
# 指定 poppler_path
poppler_path = r"C:\path\to\poppler\bin" # 替换为你的 poppler bin 目录路径
images = convert_from_path(pdf_path, poppler_path=poppler_path)
image_paths = []
for i, image in enumerate(images):
image_path = os.path.join(output_folder, f"page_{i+1}.png")
image.save(image_path, "PNG")
image_paths.append(image_path)
return image_paths
def images_to_text(image_paths):
text = ""
for image_path in image_paths:
text += pytesseract.image_to_string(image_path, lang='chi_sim') # 如果需要识别中文,指定语言为 chi_sim
return text
def pdf_to_text(pdf_path, output_folder):
# 确保输出文件夹存在
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 将 PDF 转换为图片
image_paths = pdf_to_images(pdf_path, output_folder)
# 从图片中提取文本
text = images_to_text(image_paths)
return text
# 使用示例
pdf_path = r"C:\path\to\your\pdf\file.pdf" # 替换为你的 PDF 文件路径
output_folder = r"C:\path\to\output\folder" # 替换为你的输出文件夹路径
text = pdf_to_text(pdf_path, output_folder)
print(text)
关键点说明
-
指定
tesseract
路径:- 使用
pytesseract.pytesseract.tesseract_cmd
来指定tesseract
的可执行文件路径。 - 例如:
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
。
- 使用
-
指定
poppler
路径:- 如果你使用的是
pdf2image
,需要指定poppler
的路径。 - 例如:
poppler_path = r"C:\path\to\poppler\bin"
。
- 如果你使用的是
-
语言支持:
- 如果需要识别中文,可以在
pytesseract.image_to_string
中指定语言参数lang='chi_sim'
。 - 确保你已经安装了中文语言包(
chi_sim.traineddata
),并将其放在tesseract
的tessdata
目录中。
- 如果需要识别中文,可以在
-
输出文件夹:
- 确保输出文件夹存在,如果不存在,使用
os.makedirs
创建。
- 确保输出文件夹存在,如果不存在,使用
运行流程
- 将 PDF 文件转换为图片(使用
pdf2image
)。 - 使用
pytesseract
从图片中提取文本。 - 将提取的文本输出或保存。
示例输出
假设你的 PDF 文件包含中文文本,运行代码后,text
变量将包含从 PDF 中提取的文本内容。你可以将其打印出来或保存到文件中。
# 将提取的文本保存到文件
output_text_file = os.path.join(output_folder, "extracted_text.txt")
with open(output_text_file, "w", encoding="utf-8") as f:
f.write(text)
print(f"提取的文本已保存到: {output_text_file}")
总结
- 确保
tesseract
和poppler
的路径正确。 - 如果需要识别中文,安装中文语言包并指定
lang='chi_sim'
。 - 代码会将 PDF 转换为图片,然后从图片中提取文本并保存。