python3中的Antlr4(windows)
安装教程,我参考的是:https://www.aliyun.com/jiaocheng/525558.html
为了方便大家看,内容是
1. 到官网http://www.antlr.org/download.html 或者https://pypi.python.org/pypi/antlr4-python3-runtime/下载 antlr4-python3-runtime-4.7.macosx-10.6-x86_64.exe (md5),然后双击安装;
2. 在CMD命令行下运行
pip3 install antlr4-python3-runtime
但是上述步骤是不够的,还需要设置一下环境变量,我直接用了别人的.bat,下载地址:https://github.com/jszheng/py3antlr4book, 这个地址上还有一部分示例,简直太好了。唯一可惜的是上面的.bat文件需要修改,而我就是因为忘记了改.bat而足足困了一天啊!!!
我的步骤就是:
第一步:
在CMD命令行下运行: pip3 install antlr4-python3-runtime
第二步:从https://github.com/jszheng/py3antlr4book上下载zip包,解压,运行bin文件夹下的.bat,如果有需要一定要修改啊。
第三步:
cmd中运行:
antlr4 -Dlanguage=Python3 MyGrammar.g4
其中的MyGrammar.g4是自己写的,具体怎么写,还没来得及研究。然后会自动生成:
- MyGrammarLexer.py
- MyGrammarParser.py
- MyGrammarListener.py (if you have not activated the -no-listener option)
- MyGrammarVisitor.py (if you have activated the -visitor option)
第四步:可以开始跑第一个例子了,比如我跑的是https://github.com/jszheng/py3antlr4book上的01_Hello,代码如下:
import sys
from antlr4 import *
from HelloLexer import HelloLexer
from HelloParser import HelloParser
def main(argv):
input_ = FileStream(argv[1])
lexer = HelloLexer.HelloLexer(input_)
stream = CommonTokenStream(lexer)
parser = HelloParser.HelloParser(stream)
tree = parser.r()
print(tree.toStringTree(recog=parser))
if __name__ == '__main__':
main(sys.argv)
对了,上述并不是原作者的代码,因为有错误,所以将
lexer = HelloLexer(input_)
#和
parser = HelloParser(stream)
改成了
lexer = HelloLexer.HelloLexer(input_)
#和
parser = HelloParser.HelloParser(stream)
改完了就可以运行了