tesseract_cmd 来指定 tesseract 的可执行文件路径

如果你已经在本地安装了 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)

关键点说明

  1. 指定 tesseract 路径

    • 使用 pytesseract.pytesseract.tesseract_cmd 来指定 tesseract 的可执行文件路径。
    • 例如:pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
  2. 指定 poppler 路径

    • 如果你使用的是 pdf2image,需要指定 poppler 的路径。
    • 例如:poppler_path = r"C:\path\to\poppler\bin"
  3. 语言支持

    • 如果需要识别中文,可以在 pytesseract.image_to_string 中指定语言参数 lang='chi_sim'
    • 确保你已经安装了中文语言包(chi_sim.traineddata),并将其放在 tesseracttessdata 目录中。
  4. 输出文件夹

    • 确保输出文件夹存在,如果不存在,使用 os.makedirs 创建。

运行流程

  1. 将 PDF 文件转换为图片(使用 pdf2image)。
  2. 使用 pytesseract 从图片中提取文本。
  3. 将提取的文本输出或保存。

示例输出

假设你的 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}")

总结

  • 确保 tesseractpoppler 的路径正确。
  • 如果需要识别中文,安装中文语言包并指定 lang='chi_sim'
  • 代码会将 PDF 转换为图片,然后从图片中提取文本并保存。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值