IndexError: list index out of range, substring from string

Viewed 29

I have a function for extacting a substring from a string.

And it returns the correct result. But it also returns this error code:

Traceback (most recent call last):
  File "c:\Users\engel\Documents\python\code\textFromImages.py", line 26, in <module>
    print(allSubstring[0])
IndexError: list index out of range

code fragment:

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

pdfFile = wi(
    filename="C:\\Users\\engel\\Documents\\python\\docs\\fixedPDF.pdf", resolution=300)
image = pdfFile.convert('jpeg')

imageBlobs = []


for img in image.sequence:
    imgPage = wi(image=img)
    imageBlobs.append(imgPage.make_blob('jpeg'))

extract = []
substring = 'Peen Waspeen 14x1lkg'

for imgBlob in imageBlobs:
    image = Image.open(io.BytesIO(imgBlob))
    text = pytesseract.image_to_string(image, lang='eng')
    extract.append(text)
    allSubstring = re.findall(r'{}'.format(substring),text) 
    print(allSubstring[0])

So what I have to change about this code fragment, that it wil not return the error code?

Thank you

1 Answers

Oke, this works:

    print(allSubstring[0]) if len(allSubstring) > 0 else 'null'
Related