Python - Iterate through a list of strings and group partial matching strings
fuzzy-search, grouping, python, string-matching
Solution
Sequence matcher will do the task for you. Tune the score ratio for better results.
Try this:
from difflib import SequenceMatcher
sentence_list = ["I love cat", "I love dog", "I love fish", "I hate banana", "I hate apple", "I hate orange"]
result=[]
for sentence in sentence_list:
if(len(result)==0):
result.append([sentence])
else:
for i in range(0,len(result)):
score=SequenceMatcher(None,sentence,result[i][0]).ratio()
if(score<0.5):
if(i==len(result)-1):
result.append([sentence])
else:
if(score != 1):
result[i].append(sentence)
Output:
[['I love cat', 'I love dog', 'I love fish'], ['I hate banana', 'I hate apple', 'I hate orange']]
Problem
So I have a list of strings as below: ``` list = ["I love cat", "I love dog", "I love fish", "I hate banana", "I hate apple", "I hate orange"] ``` How do I iterate through the list and group partially matching strings without given keywords. The result should like below: ``` list 1 = [["I love cat","I love dog","I love fish"],["I hate banana","I hate apple","I hate orange"]] ``` Thank you so much.