简体   繁体   English

pyparsing:命名结果?

[英]pyparsing: named results?

I am writing a parser to parse mathematical expressions, which contain variables among other things. 我正在编写一个解析器来解析数学表达式,其中包含变量等。 I want a list of all the captured variables. 我想要一个所有捕获变量的列表。 But I am only getting the last captured variable. 但我只获得最后捕获的变量。 Below is a minimal example to show the problem. 以下是显示问题的最小示例。

    >>> from pyparsing import *
    >>> var = Word(alphas)
    >>> expr = Forward()
    >>> expr << var('var') + ZeroOrMore(Literal('+') + expr)
    >>> foo = expr.parseString("x + y + z")
    >>> foo
    (['x', '+', 'y', '+', 'z'], {'var': [('x', 0), ('y', 2), ('z', 4)]})
    >>> foo['var']
    'z'

I was expecting ['x', 'y', 'z']. 我期待['x','y','z']。 I am using pyparsing version 2.1. 我正在使用pyparsing 2.1版。

By default, named results only capture the last item. 默认情况下,命名结果仅捕获最后一项。 If you use the explicit setResultsName method call, you can get all the items by adding the optional listAllMatches=True argument. 如果使用显式setResultsName方法调用,则可以通过添加可选的listAllMatches=True参数来获取所有项目。 Since you are using the shortcut form var('var') , you can get the listAllMatches behavior if you end the results name with an '*': 由于您使用的是快捷方式var('var') ,因此如果您使用'*'结束结果名称,则可以获得listAllMatches行为:

expr << var('var*') + ZeroOrMore(Literal('+') + expr)

I prefer to use the dump() method to list out the body and names from parsed results: 我更喜欢使用dump()方法从解析结果中列出正文和名称:

>>> foo = expr.parseString("x + y + z")
>>> foo.var
(['x', 'y', 'z'], {})
>>> print foo.dump()
['x', '+', 'y', '+', 'z']
- var: ['x', 'y', 'z']

By the way, because you have defined your grammar in this way, your operations will be evaluated right-to-left. 顺便说一下,因为您已经以这种方式定义了语法,所以您的操作将从右向左进行评估。 This will be okay if you only evaluate addition, but doing "3 - 5 + 2" right-to-left will give you -4, when you should get 0. Look into using infixNotation (formerly named operatorPrecedence ) to define and evaluate arithmetic and boolean expressions. 如果你只评估加法就可以了,但是从右到左做“3 - 5 + 2”会给你-4,当你得到0时。看看使用infixNotation (以前称为operatorPrecedence )来定义和评估算术和布尔表达式。 There are also several examples available on the pyparsing wiki at pyparsing.wikispaces.com. 在pyparsing.wikispaces.com上的pyparsing wiki上也有几个例子。

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

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