Home > Mobile >  Find The Best Match In List of string
Find The Best Match In List of string

Time:12-29

I have

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

I managed to get only the name using split('.') to be

target = "dexternewblood"

and

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)']

I did the same thing to end up with:

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

I wanna get the best match which is "Dexter: New Blood" if you can add way for getting index as well

CodePudding user response:

From this similar post you can use SequenceMatcher from difflib built-in module:

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 '
  • Related