问题描述
我正在尝试解析由二元运算符 +
、一元运算符 not
和可以是不是 的任何字母字符串的标识符组成的表达式不是
I'm trying to parse expressions made of the binary operator +
, the unary operator not
and identifiers that can be any alphabetical string that isn't not
from pyparsing import (
CaselessKeyword,
Combine,
Word,
alphas,
opAssoc,
infixNotation,
)
identifier = Combine(~CaselessKeyword('not') + Word(alphas))
expression = infixNotation(identifier, [
('+', 2, opAssoc.LEFT),
(CaselessKeyword('not'), 1, opAssoc.RIGHT),
]
运行
expression.parseString('a + (not b)')
满足我的期望
[['a', '+', ['not', 'b']]]
但是,没有括号
expression.parseString('a + not b')
我只得到第一个令牌:
['a']
如何在没有括号的情况下定义要工作的语言?
How can I define the language to work as I would like without the parentheses?
(在实际情况下有更多的运算符和保留字:这是解析 S3 Select 语言的一步)
(In the real case there are more operators and reserved words: this is a step towards parsing the S3 Select language)
推荐答案
在S3中NOT
比AND
更高:
运算符优先级下表按降序显示了运算符的优先级.
(来自 S3亚马逊网站).
在那个表中,NOT
在上面 AND
.
所以你的代码应该是:
identifier = Combine(~CaselessKeyword('not') + Word(alphas))
expression = infixNotation(identifier, [
(CaselessKeyword('not'), 1, opAssoc.RIGHT),
('+', 2, opAssoc.LEFT),
])
顺便说一句 - 如果NOT
被列为低于二进制 +
",则 a + not b
是无效的表达.+
需要两个运算符:一个是 a
,但 not b
不是有效的操作数.
BTW - If "NOT
is listed as a lower than the binary +
", than a + not b
is not valid expression. +
needs two operators: one is a
, but not b
is not valid operand.
顺便说一句(来自评论):请不要在同一个表达式中混用算术运算符 +
和逻辑运算符 NOT
.1 + not 2
不是一个有效的表达式.每种语言都决定如何解析这种奇怪的表达式.
BTW2 (from comments):Please don't mix +
which is an arithmetic operator and NOT
which is a logic operator in the same expression. 1 + not 2
is not a valid expression.Every language decide how to parse that's kinds of strange expressions.
这篇关于使用二元和一元运算符、保留字且不带括号解析表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!