排除字符串列表的相似率

Similarity ratio from a list of excluded strings

在比较2个字符串的相似度时,我想排除一个字符串列表,比如忽略'Texas','US'.

我尝试在 Difflib 的 SequenceMatcher 中使用参数 'isjunk':

exclusion = ['Texas', 'US']
sr = SequenceMatcher(lambda x: x in exclusion, 'Apple, Texas, US', 'Orange, Texas, US', autojunk=True).ratio()

print (sr)

相似度高达0.72,显然没有排除不需要的字符串

正确的做法是什么?

我对这个包不熟悉,但作为一个好奇的人,我用谷歌搜索了一下,并通过一些自己的例子对其进行了一些探索。 我发现了一些有趣的东西,这不是对你的问题的解决方案,它更像是对你收到的结果的借口

我发现 here:

ratio( ) returns the similarity score ( float in [0,1] ) between input strings. It sums the sizes of all matched sequences returned by function get_matching_blocks and calculates the ratio as: ratio = 2.0*M / T , where M = matches , T = total number of elements in both sequences

让我们来看一个例子:

from difflib import SequenceMatcher
exclusion = ['Texas', 'US']
a = 'Apple, Texas, US'
b = 'Orange, Texas, US'
sr = SequenceMatcher(lambda x: x in exclusion, a, b, autojunk=True)
matches = sr.get_matching_blocks()
M = sum([match[2] for match in matches])
print(matches)
ratio = 2*M/(len(a) + len(b))
print(f'ratio calculated: {ratio}')
print(sr.ratio())

我知道了:

[Match(a=4, b=5, size=12), Match(a=16, b=17, size=0)]
ratio calculated: 0.7272727272727273
0.7272727272727273

那么对于这个例子,我希望得到相同的结果:

a = 'Apple, Texas, USTexasUS'
b = 'Orange, Texas, US'

我预计额外的 TexasUS 将被忽略,因为它在 exclusion 列表中,然后 ratio 将保持不变, 让我们看看我们得到了什么:

[Match(a=4, b=5, size=12), Match(a=23, b=17, size=0)]
ratio calculated: 0.6
0.6

口粮比第一个例子少,没有任何意义。 但是如果我们深入查看输出,我们会发现匹配完全相同!那么有什么区别呢?字符串的长度(它与排除的字符串一起计算)! 如果我们坚持 link 的命名约定,T 现在更大:

T2>T1 ----> ratio2<ratio1

我建议你在匹配之前自己过滤单词,如下所示:

exclusion = ['Texas', 'US']
a = 'Apple, Texas, USTexasUS'
b = 'Orange, Texas, US'
for word2exclude in exclusion:
    a = a.replace(word2exclude,'')
    b = b.replace(word2exclude,'')
sr = SequenceMatcher(None, a, b)

希望你会发现它有用,也许不是为了解决你的问题,而是为了理解它(理解问题是解决问题的第一步!)