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()
Gives:
[('A', '123'), ('B', 'abc'), ('A', '456'), ('A', '7'), ('B', 'd')]
现在您可以迭代返回的元组,并且每个元组都标有适当的标记。
您可以更进一步,使用类来捕获类型和特定于类型的解析后逻辑,然后将该类作为表达式的解析操作传递。这将在返回的 ParseResults 中创建类的实例,然后您可以使用某种方法直接执行该实例exec
or doIt
method:
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()
Prints:
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