我希望能够解析简单的规则表达式,这些表达式可以在parsimonious中使用and和or等连接词连接在一起。
我已经尝试了一个非常基本的语法,它可以解析一个简单的表达式,但是一旦我开始引入连接词,它就失败了。
import parsimonious
grammar = parsimonious.grammar.Grammar( """
rule = (rule)+
rule = (fieldname function parameters) / (rule conjunction rule)
fieldname = space? ("field1" / "field2" / "field3") space?
function = space? ("equal to" / "not equal to") space?
parameters = space? "()" space?
conjunction = space? ("and" / "or") space?
space = ~r"\s+"
""")测试一个简单的案例:
grammar.parse("field1 equal to ()")成功解析(至少它看起来像是构建了一个节点树--我还没有深入了解它对内容的拆分有多好--但乍一看似乎还不错)
但是对于一个更复杂的情况:
grammar.parse("field1 equal to () and field2 not equal to ()")它返回IncompleteParseError: Rule 'rule' matched in its entirety, but it didn't consume all the text. The non-matching portion of the text begins with 'and field2 not equal' (line 1, column 20).
我所阐述的语法试图允许任意连接的语句,但我肯定遗漏了一些东西。
我试着调整语法,以明确顶级类和低级类之间的区别:
grammar = parsimonious.grammar.Grammar( """
rule = expr+
expr = (fieldname function parameters) / (expr conjunction expr)
fieldname = space? ("field1" / "field2" / "field3") space?
function = space? ("equal to" / "not equal to") space?
parameters = space? "()" space?
conjunction = space? ("and" / "or") space?
space = ~r"\s+"
""")现在,当运行两部分短语时:
grammar.parse("field1 equal to () and field2 not equal to ()")我得到的是RecursionError: maximum recursion depth exceeded in comparison,而不是IncompleteParseError。
发布于 2019-12-02 23:26:15
在expr的(expr conjunction expr)部分,你有一个左递归问题。因此,您需要将其分解为单独的规则,如下所示:
rule = expr+
expr = field_expr (conjunction expr)?
field_expr = fieldname function parameters
fieldname = space? ("field1" / "field2" / "field3") space?
function = space? ("not equal to" / "equal to") space?
parameters = space? "()" space?
conjunction = space? ("and" / "or") space?
space = ~r"\s+"https://stackoverflow.com/questions/57005484
复制相似问题