mercredi 28 avril 2021

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.

Aucun commentaire:

Enregistrer un commentaire