【问题标题】:Create a new .txt file for each .pdf files in a directory in python为python目录中的每个.pdf文件创建一个新的.txt文件
【发布时间】:2019-10-17 01:05:13
【问题描述】:

我的代码应该从目录中获取每个 pdf,对其进行 OCR 处理,然后为每个 OCR 处理的 pdf 返回一个 .txt 文件。 pdf 和 .txt 文件的名称应该相同,只是 .pdf 更改为 .txt。我被困在拆分输入 pdf 名称以生成具有 .txt 扩展名的 OCR 文件的相同名称的部分。目录中的示例文件如下所示:“000dbf9d-d53f-465f-a7ce-722722136fb7465.pdf”。我需要输出为“000dbf9d-d53f-465f-a7ce-722722136fb7465.txt”。此外,我的代码不会创建新的 .txt 文件,而是会在每次迭代时覆盖一个文件。我需要为每个 OCR 的 .pdf 文件创建一个新的 .txt 文件。到目前为止的代码:

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


files = glob.glob(r"D:\files\**")
for file in files:
    #print(file)
    pdf = wi(filename = file, resolution = 300)

    pdfImg = pdf.convert('jpeg')

    imgBlobs = []

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

    extracted_texts = []

    for imgBlob in imgBlobs:
            im = Image.open(io.BytesIO(imgBlob))
            text = pytesseract.image_to_string(im, lang = 'eng')
            extracted_texts.append(text)          
    with open("D:\\extracted_text\\"+ "\\file1.txt", 'w') as f:
        f.write(str(extracted_texts))

【问题讨论】:

    标签: python loops file-io directory file-handling


    【解决方案1】:

    您只需要跟踪您的文件名并在最后两行重新使用它:

    # ...
    import os
    
    
    files = glob.glob(r"D:\files\**")
    for file in files:
        #print(file)
    
        # Get the name of the file less any suffixes
        name = os.path.basename(file).split('.')[0]
    
        # ...
    
        # Use `name` from above to name your text file         
        with open("D:\\extracted_text\\" + name + ".txt", 'w') as f:
            f.write(str(extracted_texts))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 2015-08-29
      • 1970-01-01
      • 2015-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多