简体   繁体   English

使用pyparsing键入结果检查

[英]Type checking on results with pyparsing

I'm new using pyparsing, but I can't find how to solve this quite easy issue. 我是新用的pyparsing,但我找不到如何解决这个相当容易的问题。 I have (for the moment) a simple grammar, but I can' t find the way to discriminate the result of parsing according the types I defined in my grammar. 我(目前)有一个简单的语法,但我找不到根据我在语法中定义的类型来区分解析结果的方法。

Maybe it' d be easier to explain it with an example. 也许通过一个例子来解释它可能更容易。 Supposing this element: 假设这个元素:

elem = foo | bar

When I invoke: 当我调用时:

elem.parseString("...")

supposing the string matches with my grammar, how can I discriminate if it matches with ' foo' or with ' bar'? 假设字符串与我的语法匹配,我如何区分它是否与'foo'或'bar'匹配? I get an instance object of ParseResults with no such metadata. 我得到了ParseResults的实例对象,没有这样的元数据。

Thanks in advance. 提前致谢。

You could assign a name to them (a convoluted example using Literal): 您可以为它们指定一个名称(使用Literal的复杂示例):

foo = Literal('foo').setResultsName('foo')
bar = Literal('bar').setResultsName('bar')
grammar = foo | bar
parsed = grammar.parseString('bar foo')
print parsed
# (['bar'], {'bar': [('bar', 0)]})
print parsed.asDict()
# {'bar': 'bar'}

Jon Clements' answer is the correct one, here is just some extra code in support of his post, showing how to use getName() to detect which term you got: Jon Clements的答案是正确的,这里只是一些支持他的帖子的额外代码,展示了如何使用getName()来检测你得到的术语:

>>> from pyparsing import Literal, OneOrMore, Group
>>> bar = Literal('bar').setResultsName('BAR')
>>> foo = Literal('foo')('FOO') # using short form
>>> grammar = OneOrMore(Group(foo | bar))
>>> parsed = grammar.parseString('bar foo')
>>> for p in parsed: print p[0], p.getName()
... 
bar BAR
foo FOO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM