I am doing a project in Python where I require a user to input text. If the text matches a format supported by the program, it will output a response that includes a user’s key word (it is a simple chat bot). The format is stored in a text file as a user input format and an answer format.
For example, the text file looks like this, with user input on the left and output on the right:
my name is <-name> | Hi there, <-name>
So if the user writes my name is johnny, I want the program to know that johnny is the <-name> variable, and then to print the response Hi there, johnny.
Some prodding me in the right direction would be great! I have never used regular expressions before and I read an article on how to use them, but unfortunately it didn’t really help me since it mainly went over how to match specific words.
Here’s an example:
I’ll take you through it:
(?P<name>...)stores the following part (\w+) under the namenamein the match object which we’re going to use later on.This looks for the
regexin the input given. Note thatre.matchonly matches at the beginning of the input, if you don’t want that restriction usere.searchhere instead.If it matches:
match.groupdictreturns a dictionary of keys defined by(?P<name>...)and their associated matched values.**passes those key/values to.format, in this case Python will translate it tooutput.format(name='matchedname').To construct the
iodictionary from a file do something like this: