Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
传递用于执行OCR的pdf文件目录,并为Python中的每个转换文件生成.txt文件_Python_Loops_Pdf_File Handling_Python Tesseract - Fatal编程技术网

传递用于执行OCR的pdf文件目录,并为Python中的每个转换文件生成.txt文件

传递用于执行OCR的pdf文件目录,并为Python中的每个转换文件生成.txt文件,python,loops,pdf,file-handling,python-tesseract,Python,Loops,Pdf,File Handling,Python Tesseract,我有一个包含pdf文件的目录。我编写了一段代码,当您将文件名传递给wand.image类的对象时,它将执行OCR。我现在想做的是循环遍历pdf文件目录,为每个pdf生成一个OCR'd txt文件,并将其保存到某个目录中。到目前为止,我编写的代码如下: import io from PIL import Image import pytesseract from wand.image import Image as wi pdf = wi(filename = r"D:\files\aba

我有一个包含pdf文件的目录。我编写了一段代码,当您将文件名传递给wand.image类的对象时,它将执行OCR。我现在想做的是循环遍历pdf文件目录,为每个pdf生成一个OCR'd txt文件,并将其保存到某个目录中。到目前为止,我编写的代码如下:

import io
from PIL import Image
import pytesseract
from wand.image import Image as wi




pdf = wi(filename = r"D:\files\aba7d525-04b8-4474-a40d-e94f9656ed42.pdf", resolution = 300)

pdfImg = pdf.convert('jpeg')

imgBlobs = []

for img in pdfImg.sequence:
    page = wi(image = img)
    imgBlobs.append(page.make_blob('jpeg'))

extracted_text = []

for imgBlob in imgBlobs:
    im = Image.open(io.BytesIO(imgBlob))
    text = pytesseract.image_to_string(im, lang = 'eng')
    extracted_text.append(text)

print(extracted_text[0])

关于如何从OCR的pdf生成.txt文件的任何建议,请在代码末尾尝试以下内容:

with open('filename.txt', 'w') as result:
     for line in extracted_text:
          result.write(line,'\n')

问题是,如果你看到我的代码(“pdf=…”),我已经在代码中硬编码了一个文件名,但我需要在那里传递一个目录,以便该目录中的所有文件都可以进行OCR'd,并且我还需要将所有这些文件作为输出,这些文件的文件名只有.pdf被.txt替换。我该怎么做