i want to recognize if a user says somthing like "Hey David" oder "Hi Max" and then do something. i got the voice recognition and convertion but i dont know how to check for the variations like hey, hi plus the names like david or amy or whatever.
i tried to check the string with a reg ex but it only checks for the first variations.
if any(re.findall(r'hi|Hey' + r'Amy|David', string, re.IGNORECASE)):
print("test")
>Solution :
You can use regular expressions, but you’ll need to structure your regex pattern correctly. Your current approach only checks for the presence of either "Hi" or "Hey" and then one of the names "Amy" or "David" in sequence.
import re
# Example list of greetings and names to check for
greetings = ["Hi", "Hey", "Hello"]
names = ["Amy", "David", "Max"]
# Sample input text
text = "Hey David, how are you?"
# Construct a regex pattern to match variations
pattern = rf'({"|".join(greetings)})\s+({"|".join(names)})'
# The pattern will look like: (Hi|Hey|Hello)\s+(Amy|David|Max)
if re.search(pattern, text, re.IGNORECASE):
print("Recognized a greeting and name in the text.")
# Perform your action here
else:
print("No match found.")
In this code, we create lists of greetings and names you want to recognize.
The "|" character is used to create an OR condition within the pattern. We use "\s+" to match one or more spaces between the greeting and the name. The "re.IGNORECASE" flag ensures that the pattern matching is case-insensitive.