I'm trying to design an application that binds a phrase or word to some item, for example image, and saves phrase-item pair in the database. Then it receives a text, and if it contains binded substring, corresponding item should be returned. It should return only one item (first match), and longest substrings should take precedence.
I wrote a function, that returns expected values:
from operator import itemgetter
def get_item(text, bindings):
text = text.lower()
matches = []
for phrase, item in bindings:
phrase = phrase.lower()
index = text.find(phrase)
if index != -1:
matches.append((phrase, item, index))
if matches:
matches.sort(key=lambda x: len(x[0]), reverse=True)
matches.sort(key=itemgetter(2))
item_id = matches[0][1]
else:
item_id = None
return item_id
Example:
bindings = [
('i', 'item1'), ('like', 'item2'), ('i like', 'item3'), ('turtles', 'item4'),
]
text = 'I like turtles!'
print(get_item(text, bindings)) # should return item3
Is there cleaner ways to complete such task, or faster, perhaps?