python - 简约 - 规则 'rules' 完全匹配,但它没有消耗所有文本

标签 python parsing compiler-construction context-free-grammar parsimonious

我正在为表达式制作一个简单的解析器,这是我的代码:

import parsimonious as parmon

parser = parmon.Grammar(r"""
            E = E "+" E / id
            id = "0"/"1"/"2"/"3"/"4"/"5"/"6"/"7"/"8"/"9"
    """)

code = "2+2"

print(parser.parse(code))

我收到此错误:

IncompleteParseError(text, node.end, self)
parsimonious.exceptions.IncompleteParseError: Rule 'rules' matched in its entirety, but it didn't consume all the text. The non-matching portion of the text begins with '/ id
            id = "0"/"1"' (line 2, column 16).

我也尝试过 Lark-parser,但也无法解决这个问题。感谢帮助。

最佳答案

我无法提供任何关于你提到的解析器的东西。您考虑过pyparsing

  • id被定义为一位数字标记。
  • Forward表示E稍后将在代码中定义。 (这类似于过程语言中“前进”的使用。)
  • <<运算符插入 E 的定义进入其自身。括号要求“先匹配”,这意味着如果可能,将应用“或”中的第一个表达式。
  • 解析器在两个 print 内执行功能。

这是此类表达式的简单解析器。

from pyparsing import *

id = Word(nums, min=1, max=1)
E = Forward()
E << (id + '+' + E | id)

code = '2 + 2'

print (E.parseString(code))

print (E.parseString('3+4+5'))

此代码产生此结果。

['2', '+', '2']
['3', '+', '4', '+', '5']

关于python - 简约 - 规则 'rules' 完全匹配,但它没有消耗所有文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48285502/

相关文章:

java - 如何解析多个整数

java - SimpleDateFormat:无法解析的日期 MMMM yyyy

c - 简单地使用带有参数的命令 C 解析器

c - 这就像函数调用参数是在 BNF 语法中定义的吗?

python - 如何分块加载 Pickle 文件?

python - 我可以在 ASE 上移植现有的 Python 应用程序吗?

python - 尝试连接两个不同维度的数组

c++ - 将 ASCII 值分配给 Bison 中的变量

java - 如何从 Java 中的生产代码中删除调试语句

python - VirtualEnv 导入错误