Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use regular expressions in Python with placeholder text?

Tags:

python

regex

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.

like image 818
user1189336 Avatar asked Dec 06 '22 16:12

user1189336


1 Answers

Here's an example:

import re

io = [
    ('my name is (?P<name>\w+)', 'Hi there, {name}'),
]

string = input('> ')
for regex, output in io:
    match = re.match(regex, string)
    if match:
        print(output.format(**match.groupdict()))
        break

I'll take you through it:


'my name is (?P<name>\w+)'

(?P<name>...) stores the following part (\w+) under the name name in the match object which we're going to use later on.


match = re.match(regex, string)

This looks for the regex in the input given. Note that re.match only matches at the beginning of the input, if you don't want that restriction use re.search here instead.


If it matches:

output.format(**match.groupdict())

match.groupdict returns 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 to output.format(name='matchedname').


To construct the io dictionary from a file do something like this:

io = []
with open('input.txt') as file_:
    for line in file:
        key, value = line.rsplit(' | ', 1)
        io.append(tuple(key, value))
like image 185
Rob Wouters Avatar answered Dec 09 '22 16:12

Rob Wouters