如何忽略 pyparsing ParseException 并继续?

我想忽略文件中与所有预定义解析器不匹配的行并继续。我想忽略的行范围很广,我无法为每个行检查和定义解析器。


一旦 ParseException 被捕获,我就使用 try..except 和 pass。但是,解析会立即停止。


try:

    return parser.parseFile(filename, parse_all)


except ParseException, err:

    msg = 'Error during parsing of {}, line {}'.format(filename, err.lineno)

    msg += '\n' + '-'*70 + '\n'

    msg += err.line + '\n'

    msg += ' '*(err.col-1) + '^\n'

    msg += '-'*70 + '\n' + err.msg

    err.msg = msg


    print(err.msg)

    pass

即使有 ParseException,我也想继续。


四季花海
浏览 210回答 1
1回答

叮当猫咪

Pyparsing 并没有真正的“出错时继续”选项,因此您需要调整解析器,使其不会首先引发 ParseException。您可能会尝试在解析器中添加类似| SkipTo(LineEnd())('errors*')最后一招的东西。然后,您可以查看错误结果名称以查看哪些行误入歧途(或向该表达式添加解析操作以捕获更多内容,而不仅仅是当前行)。import pyparsing as ppera = "The" + pp.oneOf("Age Years") + "of" + pp.Word(pp.alphas)era.runTests("""    The Age of Enlightenment    The Years of Darkness    The Spanish Inquisition    """)印刷:The Age of Enlightenment['The', 'Age', 'of', 'Enlightenment']The Years of Darkness['The', 'Years', 'of', 'Darkness']The Spanish Inquisition    ^FAIL: Expected Age | Years (at char 4), (line:1, col:5)添加这些行并再次调用 runTests:# added to handle lines that don't matchunexpected = pp.SkipTo(pp.LineEnd(), include=True)("no_one_expects")era = era | unexpected印刷:The Age of Enlightenment['The', 'Age', 'of', 'Enlightenment']The Years of Darkness['The', 'Years', 'of', 'Darkness']The Spanish Inquisition['The Spanish Inquisition'] - no_one_expects: 'The Spanish Inquisition'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python