3

我已经开始在 python 中使用 pytesseract。当我将它传递给单引号或双引号时

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

它返回

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

我一直在寻找一种方法来逃避单引号和双引号,但它们都没有奏效。

当我自己运行 tesseract 时

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

它工作得很好。

4

1 回答 1

6

Pytesseract 使用shlex来分隔配置参数。

shlex 的转义字符是\,如果要在shlex.split()函数中插入引号,则必须使用\.

  • 如果您只想'在白名单中:

    tesseract_config = "-c tessedit_char_whitelist=blahblah\\'")
    
  • 如果您只想"

    tesseract_config = '-c tessedit_char_whitelist=blahblah\\"')
    
  • 如果你想要两者'"

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

    或者

    tesseract_config = """-c tessedit_char_whitelist=blahblah\\"\\'""")
    
于 2018-03-31T14:35:16.283 回答