我需要在一大块文本上做一些OCR,并检查它是否包含某个字符串,但由于OCR的不准确性,我需要它来检查它是否包含字符串的大约85%的匹配率。
例如,我可能会对一段文本进行光学识别,以确保它不包含no information available
,但光学识别器可能会看到n0 inf0rmation available
或错误地解释了许多字符。
在Python中有没有一种简单的方法可以做到这一点?
发布于 2012-06-01 19:31:59
正如gauden
发布的,在difflib
中使用SequenceMatcher
是一种简单的方法。使用ratio()
,从文档中返回一个介于0
和1
之间的值,该值对应于两个字符串之间的相似度:
,其中T是两个序列中元素的总数,M是匹配的数量,这是2.0*M /T。请注意,如果两个序列相同,则该值为1.0;如果它们没有任何共同之处,则为0.0。
示例:
>>> import difflib
>>> difflib.SequenceMatcher(None,'no information available','n0 inf0rmation available').ratio()
0.91666666666666663
还有一个可能对你有用的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']
更新:查找与匹配的部分子序列
要找到与三个单词序列最接近的匹配项,我会将文本拆分为单词,然后将它们分组为三个单词序列,然后应用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']
发布于 2012-06-01 19:19:49
difflib
标准库模块中的SequenceMatcher
object将直接给出一个比率:
发布于 2012-06-01 19:16:22
你可以计算Levenshtein distance。下面是一个Python实现:http://pypi.python.org/pypi/python-Levenshtein/
https://stackoverflow.com/questions/10849141
复制相似问题