python - Check if strings from a list in a text and return first longest match -
i'm trying design application binds phrase or word item, example image, , saves phrase-item pair in database. receives text, , if contains binded phrase, corresponding item should returned. should return 1 item whole text, , longest substrings should take precedence.
i wrote function, returns expected values:
from operator import itemgetter def get_item(text, bindings): text = text.lower() matches = [] 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 turtles!' print(get_item(text, bindings)) # should return item3
but there cleaner ways complete such task, or faster, perhaps?
Comments
Post a Comment