1

So, the real world context for this is a chatbot I'm working on, but here is a condensed version of what I'm trying to accomplish.

The function is supposed to take a message, look if it contains certain keywords (some are case sensitive and some aren't) and print one response. Currently my code looks something like this:

def func(msg):
    msg_low = msg.lower()
    
    if "keyword_1" in msg_low:
        print("Reaction 1")
    elif "KeYwOrD_2" in msg:
        print("Reaction 2")
    elif "keywords_3" in msg_low:
        print("Reaction 3")

and so on, it feels very wrong.

This feels like it should have a very trivial solution, but I just can't figure it out. The two biggest issues are that I want to preserve the priority of keywords and that to deal with case sensitivity I essentially deal with two different messages (msg and msg_low) in a single if-else block.

Vyralator
  • 55
  • 5
  • If you post some test messages and their responses, would be helpful – Shubham Periwal Apr 28 '21 at 09:50
  • 1
    Make a dict of keywords and reactions and loop through: `for keyword, reaction in keywords: if keyword in msg: print(reaction)` – half of a glazier Apr 28 '21 at 09:50
  • @ShubhamPeriwal Not sure how that would help, I was trying to keep it is generalized as possible so it's easier to get into, but in my example it would be something like "keyword_3 some other words KeYwOrD_2 more words" in which case the output should be "Reaction 2" – Vyralator Apr 28 '21 at 10:53
  • 1
    @halfofaglazier I've considered that, but couldn't quite get to work with case sensitive/insensitve I've already got a solution, but thanks for the reply anyways – Vyralator Apr 28 '21 at 10:54

1 Answers1

0

Can use list comprehensions to get the matches and use first match to get reaction

msg = "keyword_1 asdkflbahsjkdb KeYwOrD_2"
msg_low = msg.lower()

keywords = ["keyword_1", "KeYwOrd_2", "keywords_3"]
reactions = ["Reaction1", "Reaction2", "Reaction3"]
isCaseSensitive = [False, True, False]

#If case sensitive then check msg else msg_low
matched = [x for x in range(len(keywords)) if (isCaseSensitive[x] and keywords[x] in msg) or (keywords[x] in msg_low)]

#Get first match
reactions[min(matched)]
Shubham Periwal
  • 2,198
  • 2
  • 8
  • 26
  • Great, thanks for the quick reply. I just realized that sometimes multiple keywords can trigger the same reaction, but I think I can just stick them into a list of tuples and go from there. – Vyralator Apr 28 '21 at 10:49