[英]Pyparsing: Grammar cannot parse whitespace while parsing arithmetic expression with exponential and logarithm functions
Intention:意图:
To parse arithmetic expressions with support for logarithms and exponentials.解析支持对数和指数的算术表达式。 Any of the following expressions are valid;
以下任何表达式都是有效的;
x + y
exp(x) + y
exp(x+y)
exp(log(x)+exp(z))+exp(y)
x+log(exp(y))
x + 2
Source Code:源代码:
import pyparsing as pp
arith_expr = pp.Forward()
op = pp.oneOf("^ / * % + -")
exp_funcs = pp.Regex(r"(log|exp)(2|10|e)?")
operand = pp.Word(pp.alphas, pp.alphanums + "_") | pp.Regex(r"[+-]?\d+(:?\.\d*)?(:?[eE][+-]?\d+)?")
func_atom = operand ^ (pp.Optional(exp_funcs) + "(" + arith_expr + ")")
comp_expr = pp.Combine(func_atom + pp.ZeroOrMore(op + func_atom))
arith_expr << comp_expr
print arith_expr.parseString("exp(datasize+ 2) +3")
Observation观察
The grammar is able to parse every such arithmetic expressions but sadly fails to parse when whitespace appears around either operand or operator.该文法能够解析所有这样的算术表达式,但遗憾的是,当操作数或运算符周围出现空格时无法解析。 The grammar is unable to parse the following expressions;
语法无法解析以下表达式;
exp(x+ 2)
exp( x + 2 )
x + 2
I have tried debugging the grammar with setDebug( ) and found the following error on every such failure;我曾尝试使用 setDebug() 调试语法,并在每次此类失败时发现以下错误;
Expected ")"
I reckon Pyparsing is whitespace insensitive after going through it's documentation and my day to day use.在阅读了它的文档和我的日常使用之后,我认为 Pyparsing 对空格不敏感。 I have tried debugging with every possible change that i could.
我已尝试调试所有可能的更改。 None of them solved the issue.
他们都没有解决这个问题。 I appreciate your valuable suggestions.
我很欣赏你的宝贵建议。 :)
:)
The problem is with your use of Combine
, which squashes all the tokens together into a single token.问题在于您使用
Combine
,它将所有令牌压缩到一个令牌中。 Whitespace between tokens is ignored in pyparsing, but whitespace within a token is not. pyparsing 中会忽略标记之间的空格,但不会忽略标记内的空格。
To fix this, get rid of Combine
and then pass the result to ''.join
to get it back into one string.要解决此问题,请去掉
Combine
,然后将结果传递给''.join
以将其恢复为一个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.