【问题标题】:how to get the order in a list of the most similar string in python如何在python中最相似的字符串列表中获取顺序
【发布时间】:2013-05-29 15:59:51
【问题描述】:

我想将一个字符串与其他字符串列表进行比较,并得到最相似的。我可以在 python 中使用 difflib 来做到这一点。但是,我想做的是获取列表中的顺序。

from difflib import get_close_matches

a = ['abcde', 'efghij', 'klmno']
b = 'cdefgh'
print get_close_matches(b, a)

该代码将返回['efghij'],这是正确的。但是,如果我想得到 1,因为a[1] = 'efghij'

还有,我如何获得相似率? 我应该用SequenceMatcher(None, b, a).ratio() 再次计算它吗?

【问题讨论】:

    标签: python string compare sequence similarity


    【解决方案1】:

    这给了你第一次出现:

    >>> ['abcde', 'efghij', 'klmno'].index('efghij')
    1
    

    【讨论】:

      【解决方案2】:

      迈克斯的回答是正确的,但是如果需要速度并且您需要多次查找,那么我建议您使用字典:

      a_hash = dict(zip(a, range(len(a))))
      a_hash['efghij'] # prints 1
      

      我从未使用过 difflib,但我猜你会这样做:

      import difflib
      difflib.SequenceMatcher(None, b, a[1]).ratio()
      # or
      difflib.SequenceMatcher(None, b, a_hash[difflib.get_close_matches(b, a)]).ratio()
      # both returns 0.66666
      # presumably because both strings have de and 2/6 = 0.666
      

      这就是你想要的吗?

      【讨论】:

        猜你喜欢
        • 2015-12-19
        • 2020-06-23
        • 2023-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-25
        • 2010-10-14
        相关资源
        最近更新 更多