我已经将上面移植到Python访问者甚至Python监听器
Python listener
from antlr4 import *
from arithmeticLexer import arithmeticLexer
from arithmeticListener import arithmeticListener
from arithmeticParser import arithmeticParser
import sys
## grammar arithmetic;
##
## start : expr ;
##
## expr : left=expr op=('*'|'/') right=expr #opExpr
## | left=expr op=('+'|'-') right=expr #opExpr
## | '(' expr ')' #parenExpr
## | atom=INT #atomExpr
## ;
##
## INT : ('0'..'9')+ ;
##
## WS : [ \t\r\n]+ -> skip ;
import codecs
import sys
def dump(obj):
for attr in dir(obj):
print("obj.%s = %r" % (attr, getattr(obj, attr)))
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
class arithmeticPrintListener(arithmeticListener):
def __init__(self):
self.stack = []
# Exit a parse tree produced by arithmeticParser#opExpr.
def exitOpExpr(self, ctx:arithmeticParser.OpExprContext):
print('exitOpExpr INP',ctx.op.text,ctx.left.getText(),ctx.right.getText())
op = ctx.op.text
opchar1=op[0]
right= self.stack.pop()
left= self.stack.pop()
if opchar1 == '*':
val = left * right
elif opchar1 == '/':
val = left / right
elif opchar1 == '+':
val = left + right
elif opchar1 == '-':
val = left - right
else:
raise ValueError("Unknown operator " + op)
print("exitOpExpr OUT",opchar1,left,right,val)
self.stack.append(val)
# Exit a parse tree produced by arithmeticParser#atomExpr.
def exitAtomExpr(self, ctx:arithmeticParser.AtomExprContext):
val=int(ctx.getText())
print('exitAtomExpr',val)
self.stack.append(val)
def main():
#lexer = arithmeticLexer(StdinStream())
expression = "(( 4 - 10 ) * ( 3 + 4 )) / (( 2 - 5 ) * ( 3 + 4 ))"
lexer = arithmeticLexer(InputStream(expression))
stream = CommonTokenStream(lexer)
parser = arithmeticParser(stream)
tree = parser.start()
printer = arithmeticPrintListener()
walker = ParseTreeWalker()
walker.walk(printer, tree)
if __name__ == '__main__':
main()
Python Visitor
from antlr4 import *
from arithmeticLexer import arithmeticLexer
from arithmeticVisitor import arithmeticVisitor
from arithmeticParser import arithmeticParser
import sys
from pprint import pprint
## grammar arithmetic;
##
## start : expr ;
##
## expr : left=expr op=('*'|'/') right=expr #opExpr
## | left=expr op=('+'|'-') right=expr #opExpr
## | '(' expr ')' #parenExpr
## | atom=INT #atomExpr
## ;
##
## INT : ('0'..'9')+ ;
##
## WS : [ \t\r\n]+ -> skip ;
import codecs
import sys
class EvalVisitor(arithmeticVisitor):
def visitOpExpr(self, ctx):
#print("visitOpExpr",ctx.getText())
left = self.visit(ctx.left)
right = self.visit(ctx.right)
op = ctx.op.text;
# for attr in dir(ctx.op): ########### BEST
# print("ctx.op.%s = %r" % (attr, getattr(ctx.op, attr)))
#print("visitOpExpr",dir(ctx.op),left,right)
opchar1=op[0]
if opchar1 == '*':
val = left * right
elif opchar1 == '/':
val = left / right
elif opchar1 == '+':
val = left + right
elif opchar1 == '-':
val = left - right
else:
raise ValueError("Unknown operator " + op)
print("visitOpExpr",opchar1,left,right,val)
return val
def visitStart(self, ctx):
print("visitStart",ctx.getText())
return self.visit(ctx.expr())
def visitAtomExpr(self, ctx):
print("visitAtomExpr",int(ctx.getText()))
return int(ctx.getText())
def visitParenExpr(self, ctx):
print("visitParenExpr",ctx.getText())
return self.visit(ctx.expr())
def main():
#lexer = arithmeticLexer(StdinStream())
expression = "(( 4 - 10 ) * ( 3 + 4 )) / (( 2 - 5 ) * ( 3 + 4 ))"
lexer = arithmeticLexer(InputStream(expression))
stream = CommonTokenStream(lexer)
parser = arithmeticParser(stream)
tree = parser.start()
answer = EvalVisitor().visit(tree)
print(answer)
if __name__ == '__main__':
main()