This is what I want to achieve:
text = input("Type here: ")
reply = ["favorite" and "your" and "color"]
if any(item in text for item in reply):
print("It's Black!)
else:
print("I don't know what to say...")
` So what basically I'm saying is, if someone types "what is your favorite color" or "Tell me about your favorite color" or any other string that must contain "your", "favorite", "color", The code will print "It's Black!" However, if one of the three keywords are missing in the string, the code will print "I don't know what to say..."
How can I achieve it with minimum lines of code? because I'm trying to build a conditional chat bot type application.
text = input("Type here: ")
reply = ["favorite" and "your" and "color"]
if any(item in text for item in reply):
print("It's Black!)
else:
print("I don't know what to say...")
CodePudding user response:
if you change your code as below:
text = input("Type here: ")
reply = ["favorite", "your", "color"]
if any(item in text for item in reply):
print("It's Black!")
else:
print("I don't know what to say...")
I think you will achieve your goal
CodePudding user response:
It seems you want ALL the keywords to be in the question; then some correct code would be:
text = input("Type here: ")
reply = ["favorite", "your", "color"]
if all(item in text for item in reply):
print("It's Black!")
else:
print("I don't know what to say...")
The syntax of all
is a shortcut for 1st condition AND 2nd condition AND ..., while any
is a shortcut for 1st condition OR ... , just like in spoken English actually.
CodePudding user response:
The code should help you:
i = input("Type: ").lower()
key_words = ["color", "favorite", "your"]
matches = True
for key_word in key_words:
if not i.count(key_word):
matches = False
if matches:
print("It's black")
else:
print("I don't get it")
Just a side note: If you want to build a chatbot with this method it will scale with O(k*n) (k=number of keywords;n=length of string)