Search code examples
pythontesseractquotespython-tesseractpytesser

pytesseract tessedit_char_whitelist not accepting quote


I have started working with pytesserract in python. When i pass it single or double quote in

from PIL import Image
import pytesseract
import numpy as np

tesseract_config = r"""-c tessedit_char_whitelist=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ#'<>(){};:"""
tesseract_language = "eng"

text = pytesseract.image_to_string(Image.open('res/outc001.jpg'), lang=tesseract_language, config=tesseract_config)
print text

it returns

Traceback (most recent call last):
  File "main.py", line 15, in <module>
    text = pytesseract.image_to_string(Image.open('res/outc001.jpg'), lang=tesseract_language, config=tesseract_config).split('\n')
  File "/usr/local/lib/python2.7/dist-packages/pytesseract/pytesseract.py", line 193, in image_to_string
    return run_and_get_output(image, 'txt', lang, config, nice)
  File "/usr/local/lib/python2.7/dist-packages/pytesseract/pytesseract.py", line 140, in run_and_get_output
    run_tesseract(**kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pytesseract/pytesseract.py", line 106, in run_tesseract
    command += shlex.split(config)
  File "/usr/lib/python2.7/shlex.py", line 279, in split
    return list(lex)
  File "/usr/lib/python2.7/shlex.py", line 269, in next
    token = self.get_token()
  File "/usr/lib/python2.7/shlex.py", line 96, in get_token
    raw = self.read_token()
  File "/usr/lib/python2.7/shlex.py", line 172, in read_token
    raise ValueError, "No closing quotation"
ValueError: No closing quotation

I have been searching for a way to escape single and double quotes and none of them worked.

When i run tesseract as itself with

tesseract res/outc001.jpg tesseract_out/out001 -c "tessedit_char_whitelist=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ#\'\"<>(){};:"

it works just fine.


Solution

  • Pytesseract uses shlex to separate config arguments.

    The escape character for shlex is \, if you want to insert quotes in the shlex.split() function you must escape it with \.

    • If you want ' only in the whitelist:

      tesseract_config = "-c tessedit_char_whitelist=blahblah\\'")
      
    • If you want " only:

      tesseract_config = '-c tessedit_char_whitelist=blahblah\\"')
      
    • If you want both ' and ":

      tesseract_config = '''-c tessedit_char_whitelist=blahblah\\'\\"''')
      

      or

      tesseract_config = """-c tessedit_char_whitelist=blahblah\\"\\'""")