我可以在python中以百分比精度执行"string contains X"吗?

Jac*_*xel 14 python string ocr comparison

我需要在一大块文本上做一些OCR并检查它是否包含某个字符串,但是由于OCR的不准确性,我需要检查它是否包含类似字符串的~85%匹配.

例如,我可以OCR一大块文本以确保它不包含no information available但OCR可能会看到n0 inf0rmation available或误解多个字符.

有没有一种简单的方法在Python中执行此操作?

fra*_*xel 28

如上所述gauden,SequenceMatcherin difflib是一个简单的方法.使用ratio(),从文档中返回两个字符串之间的相似性01对应于两个字符串之间的相似性:

其中T是两个序列中元素的总数,M是匹配数,这是2.0*M/T.注意,如果序列相同则为1.0,如果它们没有任何共同点则为0.0.

例:

>>> import difflib
>>> difflib.SequenceMatcher(None,'no information available','n0 inf0rmation available').ratio()
0.91666666666666663
Run Code Online (Sandbox Code Playgroud)

还有get_close_matches一些可能对您有用的,您可以指定距离截止值,它将返回列表中该距离内的所有匹配项:

>>> difflib.get_close_matches('unicorn', ['unicycle', 'uncorn', 'corny', 
                              'house'], cutoff=0.8)
['uncorn']
>>> difflib.get_close_matches('unicorn', ['unicycle'  'uncorn', 'corny',
                              'house'], cutoff=0.5)
['uncorn', 'corny', 'unicycle']
Run Code Online (Sandbox Code Playgroud)

更新:找到部分子序列匹配

为了找到与三个单词序列的紧密匹配,我会将文本分成单词,然后将它们分成三个单词序列,然后应用difflib.get_close_matches,如下所示:

import difflib
text = "Here is the text we are trying to match across to find the three word
        sequence n0 inf0rmation available I wonder if we will find it?"    
words = text.split()
three = [' '.join([i,j,k]) for i,j,k in zip(words, words[1:], words[2:])]
print difflib.get_close_matches('no information available', three, cutoff=0.9)
#Oyutput:
['n0 inf0rmation available']
Run Code Online (Sandbox Code Playgroud)


gau*_*den 6

SequenceMatcher对象difflib的标准库模块将直接给你一个比: