regular expression dictionary search

Shawn Milochik Shawn at Milochik.com
Mon Aug 20 11:35:45 EDT 2007


#!/usr/bin/env python

import re

patterns = { 'sho.' : 6, '.ilk' : 8, '.an.' : 78 }

def returnCode(aWord):
    for k in patterns:
        p = "^%s$" % k
        regex = re.compile(p)
        if re.match(regex, aWord):
            return patterns[k]

if __name__ == "__main__":

    print "The return for 'fred' : %s" % returnCode('fred')
    print "The return for 'silk' : %s" % returnCode('silk')
    print "The return for 'silky' : %s" % returnCode('silky')
    print "The return for 'hand' : %s" % returnCode('hand')
    print "The return for 'strand' : %s" % returnCode('strand')
    print "The return for 'bank' : %s" % returnCode('bank')


Note: If a word matches more than one pattern, only one will be returned.

I'm not sure if I'm doing the patterns thing properly -- if anyone
could instruct me on whether it would be proper to declare it in the
function, or use a global declaration, please let me know. However, it
runs properly as far as I tested it.

Shawn



More information about the Python-list mailing list