Regular expression question

John Hunter jdhunter at ace.bsd.uchicago.edu
Sun Nov 24 11:48:09 EST 2002


>>>>> "jepler" == jepler  <jepler at unpythonic.net> writes:

    jepler> Anyway, here's an attempt at a Pythonic version of the
    jepler> perl code you posted.  Yes, it's longer than the Perl
    jepler> version.  

But it's also reusable.  I would make a minor modification.  Since you
are going to the trouble of writing a class, you may as well build the
dictionary for the user, since the dictionary can be built from a
sequence

import re

def whatever(v):
    return 'WhAtEvEr' + v

def want(v):
    return 'WaNt' + v


class translator:
    def __init__(self, allowed, variable):
        self._variable = variable
        #build a map of allowed names -> funcs from a list of funcs in allowed
        funcnames = map(lambda x: x.__name__, allowed)
        self.allowed = dict(zip(funcnames, allowed))

    def process(self, m):
        func = m.group(1).lower()
        return self.allowed[func](self._variable)

    def __call__(self, s):
        return re.sub('%%(.*?)%%', self.process, s)

x = translator( [whatever, want], variable='!' )

print x('I will do %%WHATEVER%%, you %%WANT%%')


Jonah, of course you would only need to bother with this class once.
Since you say you use this approach a lot, you can drop it into a
utils.py file and then just import it with

from utils import translator
# define your custom funcs
x = translator( [whatever, want], variable='!' )
print x('I will do %%WHATEVER%%, you %%WANT%%')

Which is short, clean, and fairly readable.  I came from perl to
python, and the main thing I didn't like about perl is you really had
to jump through some hoops do object oriented programming.  It's much
more natural in python, to me.

John Hunter





More information about the Python-list mailing list