为 OCR 生成相似词

Generating similar words for OCR

所以首先这是我第一次在这里提问,如果我有任何错误,请原谅我。 我的问题如下:我正在使用 python 对一堆图像进行排序。图像按许多标准排序,其中之一是图像中的文本。我已经让 OCR 正常工作,并且有一个不应该出现在图像中的“坏”词列表。问题是 OCR 经常混淆一些字母,例如 e 和 a。问题是是否有一种简单的方法可以生成看起来相似的单词。 喜欢 create_similar("test") 输出将是 ["test", "tast" "lest"] 等等。 所以我可以将其用作坏词列表并避免漏报。如果我只是缺少一个非常明显的解决方案,请告诉我。我已经尝试了几个小时了,就是无法正常工作。

我非常推荐 Peter Norvig 在 how to build a spelling corrector 上发表的这篇文章。在其中,您会发现以下功能 returns 一组所有已编辑的字符串(无论是否为单词),只需一次简单的编辑即可完成。对单词的简单编辑是删除(删除一个字母)、调换(交换两个相邻字母)、替换(将一个字母更改为另一个字母)或插入(添加一个字母)。

def edits1(word):
    "All edits that are one edit away from `word`."
    letters    = 'abcdefghijklmnopqrstuvwxyz'
    splits     = [(word[:i], word[i:])    for i in range(len(word) + 1)]
    deletes    = [L + R[1:]               for L, R in splits if R]
    transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
    replaces   = [L + c + R[1:]           for L, R in splits if R for c in letters]
    inserts    = [L + c + R               for L, R in splits for c in letters]
    return set(deletes + transposes + replaces + inserts)

对于您的用例,您可能对删除、转置和插入不感兴趣,因此您可以将其简化为:

def create_similar(word):
    "All edits that are one edit away from `word`."
    letters    = 'abcdefghijklmnopqrstuvwxyz'
    splits     = [(word[:i], word[i:])    for i in range(len(word) + 1)]
    replaces   = {L + c + R[1:]           for L, R in splits if R for c in letters}
    replaces.remove(word)
    return replaces

结果:

create_similar("test")

是:

{'aest',
 'best',
 'cest',
 'dest',
 'eest',
 'fest',
 'gest',
 'hest',
 'iest',
 'jest',
 'kest',
 'lest',
 'mest',
 'nest',
 'oest',
 'pest',
 'qest',
 'rest',
 'sest',
 'tast',
 'tbst',
 'tcst',
 'tdst',
 'teat',
 'tebt',
 'tect',
 'tedt',
 'teet',
 'teft',
 'tegt',
 'teht',
 'teit',
 'tejt',
 'tekt',
 'telt',
 'temt',
 'tent',
 'teot',
 'tept',
 'teqt',
 'tert',
 'tesa',
 'tesb',
 'tesc',
 'tesd',
 'tese',
 'tesf',
 'tesg',
 'tesh',
 'tesi',
 'tesj',
 'tesk',
 'tesl',
 'tesm',
 'tesn',
 'teso',
 'tesp',
 'tesq',
 'tesr',
 'tess',
 'tesu',
 'tesv',
 'tesw',
 'tesx',
 'tesy',
 'tesz',
 'tett',
 'teut',
 'tevt',
 'tewt',
 'text',
 'teyt',
 'tezt',
 'tfst',
 'tgst',
 'thst',
 'tist',
 'tjst',
 'tkst',
 'tlst',
 'tmst',
 'tnst',
 'tost',
 'tpst',
 'tqst',
 'trst',
 'tsst',
 'ttst',
 'tust',
 'tvst',
 'twst',
 'txst',
 'tyst',
 'tzst',
 'uest',
 'vest',
 'west',
 'xest',
 'yest',
 'zest'}