pyparsing引发空的delimitedList异常

时间:2019-03-15 17:10:46

标签: python pyparsing

我正在尝试解析列表,例如[1.0, 3.9],并且我想在列表为空时引发自定义异常。我遵循了这个https://stackoverflow.com/a/13409786/2528668,但没有成功。 这是我到目前为止的内容:

class EmptyListError(ParseFatalException):
    """Exception raised by the parser for empty lists."""

    def __init__(self, s, loc, msg):
        super().__init__(s, loc, 'Empty lists not allowed \'{}\''.format(msg))


def hell_raiser(s, loc, toks):
    raise EmptyListError(s, loc, toks[0])


START, END = map(Suppress, '[]')
list_t = START + delimitedList(pyparsing_common.sci_real).setParseAction(lambda s, loc, toks: hell_raiser(s, loc, toks) if not toks else toks) + END


tests = """
[1.0, 1.0, 1.0]
[]
[     ]
""".splitlines()

for test in tests:
    if not test.strip():
        continue
    try:
        print(test.strip())
        result = list_t.parseString(test)
    except ParseBaseException as pe:
        print(pe)
    else:
        print(result)

打印:

[1.0, 1.0, 1.0]
[1.0, 1.0, 1.0]
[]
Expected real number with scientific notation (at char 1), (line:1, col:2)
[     ]
Expected real number with scientific notation (at char 6), (line:1, col:7)

1 个答案:

答案 0 :(得分:1)

delimitedList将不匹配空白列表,因此您的解析操作将永远不会运行。我对解析器进行了少许更改,以使列表成为[]的可选内容,然后运行您的hellRaiser解析操作:

list_t = START + Optional(delimitedList(pyparsing_common.sci_real)) + END

list_t.setParseAction(lambda s, loc, toks: hell_raiser(s, loc, toks) if not toks else toks)

获得所需的输出:

[1.0, 1.0, 1.0]
[1.0, 1.0, 1.0]
[]
Empty lists not allowed '[]' (at char 0), (line:1, col:1)
[     ]
Empty lists not allowed '[]' (at char 0), (line:1, col:1)

您还可以将布尔值条件替换为解析操作,在这种情况下,只需bool-内置方法将根据令牌列表进行评估,如果为空则条件将失败。

list_t.addCondition(bool, message="Empty lists not allowed", fatal=True)

得到这个:

[1.0, 1.0, 1.0]
[1.0, 1.0, 1.0]
[]
Empty lists not allowed (at char 0), (line:1, col:1)
[     ]
Empty lists not allowed (at char 0), (line:1, col:1)

最后,请检查runTests()上的ParserElement方法。我写了“测试字符串并转储结果或捕获异常”循环很多次,我决定只添加一个测试便捷功能。