gpt4 book ai didi

Python 2.7 和 ANTLR4 : Make ANTLR throw exceptions on invalid input

转载 作者:太空狗 更新时间:2023-10-30 00:40:01 32 4
gpt4 key购买 nike

我想捕捉像这样的错误

line 1:1 extraneous input '\r\n' expecting {':', '/',}

line 1:1 mismatched input 'Vaasje' expecting 'Tafel'

我尝试在 try-catch 中包装我的函数,但正如预期的那样,这些错误只是打印语句而不是异常。我在 .g4 文件中看到了一些打开错误的例子,但所有的例子都是针对 Java 的,我似乎无法让它工作。

Python 中的 ANTLR4 是否可能抛出我可以捕获的异常?

最佳答案

我查看了 python 类并注意到它们没有 java 中用于添加和删除错误监听器的方法,这可能是 ANTLR 中的一个错误,但是 python 是 python 你可以修改成员而不需要一个 setter,如下例所示:

我通过执行 antlr4 -Dlanguage=Python2 AlmostEmpty.g4 然后输入 main.py 来运行示例


AlmostEmpty.g4

grammar AlmostEmpty;

animals: (CAT | DOG | SHEEP ) EOF;

WS: [ \n\r]+ -> skip;
CAT: [cC] [aA] [tT];
DOG: [dD] [oO] [gG];
SHEEP: [sS] [hH] [eE] [pP];

主要.py

from antlr4 import *
import sys
from AlmostEmptyLexer import AlmostEmptyLexer
from AlmostEmptyParser import AlmostEmptyParser
from antlr4.error.ErrorListener import ErrorListener

class MyErrorListener( ErrorListener ):

def __init__(self):
super(MyErrorListener, self).__init__()

def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):
raise Exception("Oh no!!")

def reportAmbiguity(self, recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs):
raise Exception("Oh no!!")

def reportAttemptingFullContext(self, recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs):
raise Exception("Oh no!!")

def reportContextSensitivity(self, recognizer, dfa, startIndex, stopIndex, prediction, configs):
raise Exception("Oh no!!")

if __name__ == "__main__":
inputStream = StdinStream( )
lexer = AlmostEmptyLexer(inputStream)
# Add your error listener to the lexer if required
#lexer.removeErrorListeners()
#lexer._listeners = [ MyErrorListener() ]
stream = CommonTokenStream(lexer)
parser = AlmostEmptyParser(stream)
# As mentioned in the comments by @Tim Stewart instead of doing this:
# parser._listeners = [ MyErrorListener() ]
# you can do this:
parser.addErrorListener( MyErrorListener() )
tree = parser.animals()

关于Python 2.7 和 ANTLR4 : Make ANTLR throw exceptions on invalid input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32224980/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com