Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python find the closest matching sentence

Tags:

python

I am trying to get a list of tracks (songs) from an album and for a given track I would like to get all the ones that matched similarly. I have mentioned the example below, any ideas on how to proceed with this in python? Seems like difflib.get_close_matches just works for single words and not a sentence.

Eample: (to find anything that contained the string 'Around the world'

tracks = ['Around The World (La La La La La) (Radio Version)', 'Around The World (La La La La La) (Alternative Radio Version)', 'Around The World (La La La La La) (Acoustic Mix)', 'Around The World (La La La La La) (Rucegsegger#Wittwer Club Mix)', 'World In Motion','My Heart Beats Like A Drum (Dam Dam Dam)','Thinking Of You','Why Oh Why','Mistake No. 2','With You','Love Is Blind','Lonesome Suite','Let Me Come & Let Me Go']

Output:

 Around The World (La La La La La) (Radio Version)
 Around The World (La La La La La) (Alternative Radio Version)
 Around The World (La La La La La) (Acoustic Mix)
 Around The World (La La La La La) (Rüegsegger#Wittwer Club Mix)
like image 609
Prem Minister Avatar asked Oct 22 '25 16:10

Prem Minister


1 Answers

difflib.get_close_matches can work with strings (other than single words). In this case, you need to lower the cutoff (the default is 0.6), and raise n, the maximum number of matches:

In [19]: import difflib

In [20]: tracks = ['Around The World (La La La La La) (Radio Version)', 'Around The World (La La La La La) (Alternative Radio Version)', 'Around The World (La La La La La) (Acoustic Mix)', 'Around The World (La La La La La) (Rucegsegger#Wittwer Club Mix)', 'World In Motion','My Heart Beats Like A Drum (Dam Dam Dam)','Thinking Of You','Why Oh Why','Mistake No. 2','With You','Love Is Blind','Lonesome Suite','Let Me Come & Let Me Go']

In [21]: difflib.get_close_matches('Around the world', tracks, n = 4,cutoff = 0.3)
Out[21]: 
['Around The World (La La La La La) (Acoustic Mix)',
 'Around The World (La La La La La) (Radio Version)',
 'Around The World (La La La La La) (Alternative Radio Version)',
 'Around The World (La La La La La) (Rucegsegger#Wittwer Club Mix)']
like image 191
unutbu Avatar answered Oct 24 '25 05:10

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!