简体   繁体   中英

How to read all pdf files in a directory and convert to text file using tesseract python 3?

How to read all pdf files in a directory and convert to text file using tesseract python 3?

The below code is for reading one pdf file and convert to text file.

But i want to read all pdf files in a directory and convert to text file using tesseract python 3

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

 pdf_filename = "pdffile_name.pdf"
 txt_filename = "text_file_created.txt"

 def tesseract(pdf_filename,txt_filename): 
      PDF_file = pdf_filename
      pages = convert_from_path(PDF_file, 500)  
      image_counter = 1

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

filelimit = image_counter-1
outfile = txt_filename
f = open(outfile, "a",encoding = "utf-8") 

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

f.close() 
f1 = open(outfile, "r",encoding = "utf-8") 
text_list = f1.readlines()
return text_list

tesseract(pdf_filename,txt_filename)`enter code here`

i have code for reading pdf files in a directory but i dont know to combine this code with above code

def readfiles():
os.chdir(path)
pdfs = []
for file_list in glob.glob("*.pdf"):
    print(file_list)
    pdfs.append(file_list)

readfiles()

Simply convert the variable pdf_filename to a list using this code snippet:

import glob

pdf_filename = [f for f in glob.glob("your_preferred_path/*.pdf")]

which will get you all the pdf files you want and store it into a list.

Or simply use any of the methods posted here:

How do I list all files of a directory?

Once you do that, you now have a list of pdf files.

Now iterate over the list of pdfs, one at a time, which will give you a list of test files.

You can use it something like this code snippet:

for one_pdf in pdf_filename:

#* your code to convert the files *#

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM