python - 在 pyparsing 中强制在标记之间添加空格

标签 python pyparsing

我正在尝试使用 pyparsing 在 Python 中构建一个简单的 lisp 解释器。我已经定义了语言:

def parse(program):
    _int = pp.Word(pp.nums).setParseAction(lambda s, l, t: [int(t[0])])
    _float = pp.Combine(pp.Word(pp.nums) + '.' +
                        pp.Word(pp.nums)).setParseAction(lambda s, l, t: [float(t[0])])
    number = _int ^ _float

    extended_chars = "!$%&*+-./:<=>?@^_~"
    symbol = pp.Word(pp.alphas + extended_chars, pp.alphanums + extended_chars)

    atom = number ^ symbol
    _list = pp.Forward()
    _list << pp.nestedExpr(opener="(", closer=")", content=atom)
    exp = atom ^ _list

    return exp.parseString(program, parseAll=True).asList()

这基本上可以工作,但它解析:

parse('(1a)') => [[1, 'a']]

这应该被解释为无效语法。我认为这是因为解析器不需要 nestedExpr 中的标记之间有空格。如何强制间距?

最佳答案

我不确定您是否真的想强制使用空格,“1+3”不也应该有效吗?

相反,请通过添加 asKeyword=True 关键字参数来修改您的 Word 表达式。

需要注意的是,nestedExpr 是一个非常简单的解析器,如果要解析嵌套表达式的内容,那么您应该使用递归解析器,或者可能使用 infixNotation 。在这个答案中查看更多内容:How do I implement this in ply, given how pyparsing works

关于python - 在 pyparsing 中强制在标记之间添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55427912/

相关文章:

Python错误: Cannot find the file specified

python - 使用鼠标移动 tkinter Canvas

python - 如何创建自定义 crontab?

python - Pyparsing 使用 Forward 解析递归表达式

recursion - pyparsing 逗号分隔列表内的递归语法空间分隔列表

python - PyParsing 中的简单递归下降

python - 各种 Python 实现的优缺点是什么?

python - 如何手动关闭BaseHTTPServer中的连接?

python - 如何让 PyParsing 识别\x 转义符?

python - pyparsing:嵌套计数数组?