July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Michael Robin
You need to use regular expressions to match strings and then automatically call functions with arguments based on the matched strings.
Once again, a class offers a good way to package together some state and some behavior:
import re
class Dispatcher:
def _dispatch(self, cmdList, str):
""" Find a match for str in the cmdList and call the associated
method with arguments that are the matching grouped subexpressions
from the regex.
"""
for comment, pattern, command in cmdList:
found = pattern.match(str) # or, use .search( )
if found: return command(self, *found.groups( ))
def runCommand(self, cmd):
self._dispatch(Commands, cmd)
# example methods
def cmd1(self, num, name):
print "The number for %s is %d" % (name, int(num))
return 42
def cmd2(self, partnum):
print "Widget serial #: %d" % int(partnum)
Commands = [
[ 'Number-to-name correspondence',
r'X (?P<num>\d+),(?P<name>.*)$',
Dispatcher.cmd1],
[ 'Extract Widget part-number',
r'Widget (?P<partnum>.*)$',
Dispatcher.cmd2],
]
# Prepare the Commands list for execution by compiling each re for cmd in Commands:
try:
cmd[1] = re.compile( cmd[1] )
except:
print "Bad pattern for %s: %s" % ( cmd[0], cmd[1] )In Python, it’s generally best to compile regular
expressions into re objects. The
re module does some caching of string-form regular expressions that you use directly, but it’s still better to make sure that regular expressions are not needlessly recompiled. ...
Read now
Unlock full access