template strings for matching?

Paul McGuire ptmcg at austin.rr.com
Thu Oct 9 15:49:43 CEST 2008

Pyparsing makes building expressions with named fields pretty easy.

from pyparsing import Word, alphas

wrd = Word(alphas)

templ = "The" + wrd("object") + "in" + wrd("location") + \
    "stays mainly in the" + wrd("subloc") + "."

tests = """\
    The rain in Spain stays mainly in the plain.
    The snake in plane stays mainly in the cabin.
    In Hempstead, Haverford and Hampshire hurricanes hardly ever
for t in tests:
    t = t.strip()
        match = templ.parseString(t)
        print match.object
        print match.location
        print match.subloc
        print "Fields are: %(object)s %(location)s %(subloc)s" % match
        print "'" + t + "' is not a match."

Read more about pyparsing at http://pyparsing.wikispaces.com.
-- Paul

More information about the Python-list mailing list