我想用pyparsing解析一些单词和一些数字。简单吧。
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
上面的代码打印['123', 'abc', '456', '7', 'd']
。一切顺利。现在我想用这些解析的值做一些工作。对于此任务,我需要知道它们是否与A
或B
匹配。有没有办法区分这两者。
我在一些研究后发现的唯一内容是items
类的ParseResults
方法。但它只返回[('A', '7'), ('B', 'd')]
,只返回最后两个匹配。
我的计划/目标如下:
for elem in result:
if elem.is_of_type('A'):
# do stuff
elif elem.is_of_type('B'):
# do something else
如何区分A
和B
?
答案 0 :(得分:7)
使用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
答案 1 :(得分:3)
我不完全确定原因,但在您的.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,我不确定这是否是规范正确的做法,但它似乎有效。
答案 2 :(得分: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'