【问题标题】:Why is my code only creating a jpeg from the last page of the PDF and therefore only writing the last page to a text file?为什么我的代码只从 PDF 的最后一页创建 jpeg,因此只将最后一页写入文本文件?
【发布时间】:2021-03-19 15:05:15
【问题描述】:

我需要从 PDF 中为某些关键字抓取大量文本,然后在找到的页面上列出这些关键字。诚然,我对 Python 非常陌生,并且从简单地遵循从 PDF 到 JPEG 并将其写入文本的教程开始。但是,即使这样,我也遇到了一些问题。我的问题是,虽然我似乎能够将 some 这个 PDF 转换为 txt,但它只占用一页,即最后一页。我的问题是为什么?我该如何解决这个问题?

谢谢

from PIL import Image 
import pytesseract 
import sys 
from pdf2image import convert_from_path 
import os 

PDF_file = "file2.pdf"
  
  
pages = convert_from_path(PDF_file, 500) 
  
image_counter = 1
  
for page in pages: 
  
   
    filename = "page_"+str(image_counter)+".jpg"
      
    page.save(filename, 'JPEG') 
  
    image_counter = image_counter + 1
  

filelimit = image_counter-1
  
outfile = "out_text.txt"
  

f = open(outfile, "a") 
  
for i in range(1, filelimit + 1): 
  
    
          
    text = str(((pytesseract.image_to_string(Image.open(filename))))) 
  
   
    text = text.replace('-\n', '')     
  
    f.write(text) 
  
f.close()

【问题讨论】:

    标签: python pdf python-tesseract


    【解决方案1】:

    问题出在filename 声明中。

    当第一个循环结束时:

    for page in pages: 
        filename = "page_"+str(image_counter)+".jpg"
        page.save(filename, 'JPEG') 
        image_counter = image_counter + 1
    

    您的 filename 变量设置为最终的 image_counter。当您读取使用 filename 变量时,您会读取 1filelimit + 1 时间的最后一张图像。

    一种解决方案是在第二个循环中重新声明filename

    for i in range(1, filelimit + 1): 
        filename = "page_"+str(i)+".jpg"
        text = str(((pytesseract.image_to_string(Image.open(filename))))) 
        text = text.replace('-\n', '')     
        f.write(text) 
      
    f.close()
    

    这应该可以解决分别读取每个文件名的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多