【问题标题】:Find The Best Match In List of string在字符串列表中查找最佳匹配
【发布时间】:2021-12-28 20:29:59
【问题描述】:

我有

target = "dexter.new.blood.S01EP07.somerandomstring.mkv"

我设法只使用split('.') 获取名称 成为

target = "dexternewblood"

list = ['Dexter - Eighth Season (2013)', 'Dexter - Seventh Season  (2012)', 'Dexter - Fourth Season (2009)', 'Dexter - Third Season (2008)', 'Dexter - Sixth Season (2011)', 'Dexter - Fifth Season (2010)', 'Dexter: New Blood - First Season (2021)', 'Dexter - First Season (2006)', 'Dexter - Second Season (2007)']

我做了同样的事情以结束:

list = ['Dexter ', 'Dexter ', 'Dexter ', 'Dexter ', 'Dexter ', 'Dexter ', 'Dexter: New Blood ', 'Dexter ', 'Dexter ']

我想得到最好的比赛,那就是“德克斯特:新血液” 如果您也可以添加获取索引的方法

【问题讨论】:

  • 欢迎来到 StackOverflow!您能否严格定义“最佳匹配”的含义?到目前为止,您尝试了哪些方法,哪些方法对您的尝试无效?
  • “我想得到最好的匹配是“德克斯特:新血液”” 为什么这是最好的匹配?是什么规则告诉你的?如果我说最好的匹配是“Dexter”,为什么我错了?
  • 我不想要完全匹配最好的匹配就可以了
  • 你说德克斯特并没有错,但在这种情况下它并不接近我想要的
  • @Khalid-elhirche 正如其他人所说,您必须确切地说明您所说的“最佳匹配”是什么意思(即,一条规则说明一个匹配是否优于其他)以便我们能够帮助您。例如,也许您可​​以使用Levenshtein distance 来表示匹配的好坏。

标签: python python-3.x python-2.7


【解决方案1】:

从这个similar post你可以使用来自SequenceMatcherSequenceMatcher内置模块:

from difflib import SequenceMatcher

target = "dexternewblood"
lst = ['Dexter ', 'Dexter ', 'Dexter ', 'Dexter ', 'Dexter ', 'Dexter ', 'Dexter: New Blood ', 'Dexter ', 'Dexter ']

a = [SequenceMatcher(None, i, target).ratio() for i in lst]

index = a.index(max(a)) # 6
match = lst[index] # 'Dexter: New Blood '

【讨论】:

    猜你喜欢
    • 2016-07-01
    • 2015-08-15
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    相关资源
    最近更新 更多