SequenceMatcher.ratio如何在difflib中工作

2024-05-29 03:24:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我在尝试python的difflib模块时遇到了SequenceMatcher。所以,我尝试了下面的例子,但不明白发生了什么。

>>> SequenceMatcher(None,"abc","a").ratio()
0.5

>>> SequenceMatcher(None,"aabc","a").ratio()
0.4

>>> SequenceMatcher(None,"aabc","aa").ratio()
0.6666666666666666

现在,根据ratio

Return a measure of the sequences' similarity as a float in the range [0, 1]. Where T is the total number of elements in both sequences, and M is the number of matches, this is 2.0*M / T.

所以,对我来说:

  1. T=4M=1so比率2*1/4 = 0.5
  2. T=5M=2so比率2*2/5 = 0.8
  3. T=6M=1so比率2*1/6.0 = 0.33

根据我的理解,T = len(aabc) + len(a)M=2因为aaabc中出现两次。

那么,我错在哪里?我错过了什么。?

HereSequenceMatcher.ratio()的源代码


Tags: 模块oftheinnonenumberlenis
1条回答
网友
1楼 · 发布于 2024-05-29 03:24:55

你第一个案子是对的。在第二种情况下,只有来自aabc的一个a匹配,所以M=1。在第三个示例中,这两个as匹配,因此M=2。

[p.S.:您指的是古老的Python2.4源代码。当前源代码位于hg.python.org。]

相关问题 更多 >

    热门问题