如何使用带antlr4的python2运行时打印解析树 [英] how print parse-tree using python2 runtime with antlr4

查看:171
本文介绍了如何使用带antlr4的python2运行时打印解析树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 antlr4版本4.4 python2运行时.语法来自antlr4,第6页,文件: Hello.g4 :

I'm trying to use antlr4 version 4.4 and the python2 runtime. The grammar is from the antlr4 book, page 6, file: Hello.g4:

grammar Hello;           
r  : 'hello' ID ;
ID : [a-z]+ ;
WS : [ \t\r\n]+ -> skip ;

然后我用命令

antlr4 -Dlanguage=Python2 Hello.g4

然后生成

文件 HelloLexer.py HelloParser.py HelloListener.py .我制作了一个主程序test.py来测试生成的python解析器:

the files HelloLexer.py, HelloParser.py and HelloListener.py among other, are then generated. I make a main program test.py to test the generated python parser:

from antlr4 import *
from HelloLexer import HelloLexer
from HelloParser import HelloParser

def main(argv):
    input = FileStream(argv[1])
    lexer = HelloLexer(input)
    stream = CommonTokenStream(lexer)
    parser = HelloParser(stream)
    tree = parser.r()
    print tree.toStringTree(parser)        <= the problem is here!

if __name__ == '__main__':
    import sys
    main(sys.argv)

一切似乎都正常,除了我无法打印分析树.

Everything seems works ok, except that I can't print the parse tree.

C:\Users\LG\antlr\tpantlr2-code\code\install>Test.py data.txt
Traceback (most recent call last):
  File "C:\Users\LG\antlr\tpantlr2-code\code\install\Test.py", line 15, in <module>
    main(sys.argv)
  File "C:\Users\LG\antlr\tpantlr2-code\code\install\Test.py", line 11, in main
    print tree.toStringTree(parser)
  File "C:\Python27\lib\site-packages\antlr4\RuleContext.py", line 181, in toStringTree
    return Trees.toStringTree(self, ruleNames=ruleNames, recog=recog)
  File "C:\Python27\lib\site-packages\antlr4\tree\Trees.py", line 48, in toStringTree
    s = escapeWhitespace(cls.getNodeText(t, ruleNames), False)
  File "C:\Python27\lib\site-packages\antlr4\tree\Trees.py", line 68, in getNodeText
    return ruleNames[t.getRuleContext().getRuleIndex()]
TypeError: 'HelloParser' object does not support indexing

我还没有弄清楚问题出在哪里.

I haven't figured out yet what the problem is.

推荐答案

您似乎使用了错误的toStringStree函数.

It looks like you took the wrong toStringStree function.

看看这说明了错误消息对象不支持索引".您选择的函数需要规则名称列表,而不是解析器.

This explains the error message "object does not support indexing". The function you chose expects a list of rule names and not the parser.

这篇关于如何使用带antlr4的python2运行时打印解析树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆