0

How to search for particular types of words from a list in a sentence given in the user input?

I found out that by importing re and using re.search I can search for a particular word in a sentence or a whole text. import re user_input = input().lower() if re.search('food', user_input): print ("Are you a foodie?") else: print('cool, bro') In the code below this text I am using the if statement to find if a whole expression is in the list(ex. greetings) import random greeings = ["hello", "hi", "greetings", "sup", "what's up", "hey"] response = ['hey', 'Good morning', "hi", "hi there", "hello"] user_input =input().lower() if user_input in greetings: random_response = random.choice(response) print(random_response) My question is: How can I substitute the word 'food' in the first code so that the program is looking through a whole list of words like the second code's greetings list?

7th Mar 2019, 4:56 AM
Ядрото
Ядрото - avatar
2 odpowiedzi
+ 6
from random import choice import re greetings = ("hello", "hi", "greetings", "sup", "what's up", "hey") response = ('hey', 'Good morning', "hi", "hi there", "hello") user_input = input().lower() if any(re.search(r'\b' + greeting + r'\b', user_input) for greeting in greetings): print(choice(response)) else: print('Try again') ~~ You can pre-compile the regex pattern as well: pattern = re.compile('|'.join(r'(\b' + greeting + r'\b)' for greeting in greetings)) if pattern.search(input().lower()): print(choice(response)) else: print('Try again')
7th Mar 2019, 5:59 AM
Anna
Anna - avatar
+ 4
import re, random greetings = ["hello", "hi", "greetings", "sup", "what's up", "hey"] response = ["hey", "Good morning", "hi", "hi there", "hello"] user_input = input().lower() if any(re.fullmatch(user_input, word) for word in greetings): random_response = random.choice(response) print(random_response) else: print("Try again")
7th Mar 2019, 5:24 AM
Diego
Diego - avatar