[Tutor] pyparsing complex search

pedro pedrooconnell at gmail.com
Thu Jul 16 22:55:16 CEST 2009


Hi, well mabe it's not so complex (just for me).
I have this code which works fine:
#start###########################################################
from pyparsing import *

data = """23 different size pry bars
hammer the pitchfork
pound felt paper staple the felt paper every to inches staple hammer"""

def reportACertainWord( st , locn , toks ):
    theWord = toks[0]
    if theWord == Word(nums):
        print "Found '%s' on line %d at column %d" % (theWord, lineno( 
locn , st ), col( locn , st ))
        print "The full line of text was:"
        print "'%s'" % line( locn , st )
        print (" "*col( locn , st ))+" ^"
        print

returnedWords = Word(alphanums).setParseAction( reportACertainWord )
OneOrMore(returnedWords).parseString(data)
#end################################################################

But what I want to search for is any number plus the word after it.
I thought the following code would do it but it doesn't (I only changed 
the if line).
Any help would be appreciated.
Pete

#start###########################################################
from pyparsing import *

data = """23 different size pry bars
hammer the pitchfork
pound felt paper staple the felt paper every to inches staple hammer"""

def reportACertainWord( st , locn , toks ):
    theWord = toks[0]
    if theWord == Word(nums) + Word( alphas ):
        print "Found '%s' on line %d at column %d" % (theWord, lineno( 
locn , st ), col( locn , st ))
        print "The full line of text was:"
        print "'%s'" % line( locn , st )
        print (" "*col( locn , st ))+" ^"
        print

returnedWords = Word(alphanums).setParseAction( reportACertainWord )
OneOrMore(returnedWords).parseString(data)
#end################################################################




More information about the Tutor mailing list