So I'm writing a python bot that would respond to a users input based on some key words in the users input. My program takes a spanish input and displays a spanish output. They are very simple phrases. If the input is "Yo no estoy feliz", which means "I am not happy", the expected output should be "¿Porqué no estás feliz?", which means "why are you not happy". If the input is "Yo estoy feliz", which means "I am happy", the expected output should be "¿Porqué estás feliz?".
I could handle the positive and negative scenarios with two different regex expressions but I'm trying to do it with one regex expression. I tried using optional grouping to achieve this but I didn't get the desired result if my input is "Yo estoy feliz". However, I get the desired result with "Yo no estoy feliz". I'm very new to regex and I would appreciate any guidance on this. Below is the code and some comments
import sys
import re
# Run from command line as: python [progname.py] "Yo no estoy feliz."
# INPUT: Yo no estoy feliz. [I am not happy]
# EXPECTED OUTPUT : ¿Porqué no estás feliz? [Why are you not happy]
###### Translation #######
# ¿Porqué no estás feliz? == Why are you not happy?
# ¿Porqué estás feliz? == Why are you happy
def caseHandler(regExInput):
return re.compile(regExInput, re.IGNORECASE)
def bot(userInput):
reply = ""
expression = caseHandler(r'(.* )?(?:no)? estoy (.* )?(.+)\b')
if (expression.match(userInput)):
groupName = expression.search(userInput) # Ensures if input matches regex
if (groupName.group(4) and groupName.group(2)):
reply = "¿Porqué no estás " + groupName.group(4) + "?" # presence of "no" in input
elif (groupName.group(4)):
reply = "¿Porqué estás " + groupName.group(4) + "?" # absence of "no" in INPUT
else:
reply = "Cuéntame más." # Tell me more
else:
reply = "Cuéntame más." # Tell me more
return reply
if (len(sys.argv) < 2):
print("Please provide an input phrase")
else:
print(bot(str(sys.argv[1])))
You can try something like this:
import sys;
import re;
def caseHandler(regExInput):
return re.compile(regExInput, re.IGNORECASE)
def bot(userInput):
expression = caseHandler(r'((?:\bno )?)estoy +(.+)\b')
m = expression.search(userInput)
if m:
reply = "¿Porqué " + m.group(1) + "estás " + m.group(2) + "?"
else:
reply = "Cuéntame más."
return reply
if (len(sys.argv) < 2):
print("Please provide an input phrase")
else:
print(bot(str(sys.argv[1])))