pythonif-statementparadigms

Python: Make program react to keywords in a string without endless if-else nightmare


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.


Solution

  • 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)]