Спасибо Хэмишу Грубиджану за эту идею.Каждый?в моем ocr'd имена могут быть где угодно от 0 до 3 букв.Я расширяю каждую строку до списка возможных расширений:
>>> list(expQuestions("?flcopt?"))
['flcopt', 'flcopt@', 'flcopt@@', 'flcopt@@@', '@flcopt', '@flcopt@', '@flcopt@@', '@flcopt@@@', '@@flcopt', '@@flcopt@', '@@flcopt@@', '@@flcopt@@@', '@@@flcopt', '@@@flcopt@', '@@@flcopt@@', '@@@flcopt@@@']
, затем я расширяю оба и использую его функцию сопоставления, которую я назвал matchats
:
def matchOCR(l, r):
for expl in expQuestions(l):
for expr in expQuestions(r):
if matchats(expl, expr):
return True
return False
Работаетпо желанию:
>>> matchOCR("Ro?co?er", "?flcopt?")
True
>>> matchOCR("Ro?co?er", "?flcopt?z")
False
>>> matchOCR("Ro?co?er", "?flc?pt?")
True
>>> matchOCR("Ro?co?e?", "?flc?pt?")
True
Функция сопоставления:
def matchats(l, r):
"""Match two strings with @ representing exactly 1 char"""
if len(l) != len(r): return False
for i, c1 in enumerate(l):
c2 = r[i]
if c1 == "@" or c2 == "@": continue
if c1 != c2: return False
return True
и функция расширения, где cartesian_product
делает именно это:
def expQuestions(s):
"""For OCR w/ a questionmark in them, expand questions with
@s for all possibilities"""
numqs = s.count("?")
blah = list(s)
for expqs in cartesian_product([(0,1,2,3)]*numqs):
newblah = blah[:]
qi = 0
for i,c in enumerate(newblah):
if newblah[i] == '?':
newblah[i] = '@'*expqs[qi]
qi += 1
yield "".join(newblah)