Distinguish matches in pyparsing

I want to parse some words and some numbers with pyparsing. Simple right.

from pyparsing import *

A = Word(nums).setResultsName('A')
B = Word(alphas).setResultsName('B')
expr = OneOrMore(A | B)

result = expr.parseString("123 abc 456 7 d")
print result

The code above prints ['123', 'abc', '456', '7', 'd']. So it worked. Now I want to do some work with these parsed values. For this task, I need to know if they match Aor B. Is there a way to distinguish between the two.

The only thing I found after some research is the itemsclass method ParseResults. But it [('A', '7'), ('B', 'd')]only returns the last two matches.

My plan / goal is this:

for elem in result:
    if elem.is_of_type('A'):
        # do stuff
    elif elem.is_of_type('B'):
        # do something else

How to distinguish Aand B?

+4
source share
3 answers

getName(). , , :

def makeDecoratingParseAction(marker):
    def parse_action_impl(s,l,t):
        return (marker, t[0])
    return parse_action_impl

A = Word(nums).setParseAction(makeDecoratingParseAction("A"))
B = Word(alphas).setParseAction(makeDecoratingParseAction("B"))
expr = OneOrMore(A | B)

result = expr.parseString("123 abc 456 7 d")
print result.asList()

:

[('A', '123'), ('B', 'abc'), ('A', '456'), ('A', '7'), ('B', 'd')]

, .

, -, . ParseResults, exec doIt:

class ResultsHandler(object):
    """Define base class to initialize location and tokens.
       Call subclass-specific post_init() if one is defined."""
    def __init__(self, s,locn,tokens):
        self.locn = locn
        self.tokens = tokens
        if hasattr(self, "post_init"):
            self.post_init()

class AHandler(ResultsHandler):
    """Handler for A expressions, which contain a numeric string."""
    def post_init(self):
        self.int_value = int(self.tokens[0])
        self.odd_even = ("EVEN","ODD")[self.int_value % 2]
    def doIt(self):
        print "An A-Type was found at %d with value %d, which is an %s number" % (
                self.locn, self.int_value, self.odd_even)

class BHandler(ResultsHandler):
    """Handler for B expressions, which contain an alphabetic string."""
    def post_init(self):
        self.string = self.tokens[0]
        self.vowels_count = sum(self.string.lower().count(c) for c in "aeiou")
    def doIt(self):
        print "A B-Type was found at %d with value %s, and contains %d vowels" % (
                self.locn, self.string, self.vowels_count)


# pass expression-specific handler classes as parse actions
A = Word(nums).setParseAction(AHandler)
B = Word(alphas).setParseAction(BHandler)
expr = OneOrMore(A | B)

# parse string and run handlers
result = expr.parseString("123 abc 456 7 d")
for handler in result:
    handler.doIt()

An A-Type was found at 0 with value 123, which is an ODD number
A B-Type was found at 4 with value abc, and contains 1 vowels
An A-Type was found at 8 with value 456, which is an EVEN number
An A-Type was found at 12 with value 7, which is an ODD number
A B-Type was found at 14 with value d, and contains 0 vowels
+5

, , .setResultsName() listAllMatches=True ( False). , , result , , result.

from pyparsing import *

#                                    โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“
A = Word(nums  ).setResultsName('A', listAllMatches=True)
B = Word(alphas).setResultsName('B', listAllMatches=True)
expr = OneOrMore(A | B)

result = expr.parseString("123 abc 456 7 d")

for elem in result:
    if elem in list(result['A']):
        print(elem, 'is in A')
    elif elem in list(result['B']):
        print(elem, 'is in B')

:

123 is in A
abc is in B
456 is in A
7 is in A
d is in B

kludgey, , , , , .

+3

. ParseResults getName(). result getName() , ParseResults . - A B Groups. , , .

from pyparsing import *

A = Group(Word(nums)).setResultsName('A', listAllMatches=True)
B = Group(Word(alphas)).setResultsName('B', listAllMatches=True)
expr = OneOrMore(A | B)

result = expr.parseString("123 abc 456 7 d")

for i in  result:
    if i.getName() == 'A':
       print i[0], 'is a number'
    elif i.getName() == 'B':
       print i[0], 'is a string'
+2

All Articles