英文:
How to print the tokens like with "-tokens" in the terminal?
问题
在终端(或控制台)中,我可以使用以下命令grun Exp eval -tokens
,但我如何从Java中执行这个操作呢?我发现可以使用如下方式来实现类似于-tree
的功能:
ParseTree tree = parser.eval();
System.out.println(tree.toStringTree(parser));
但我找不到类似于-tokens
的功能。
编辑 1:我找到了使用lexer.reset()
的方式:
lexer.reset();
for (Token token: lexer.getAllTokens()) {
System.out.println(token);
}
但是这些标记只是像<4>
这样的数字,我想要获取它们的实际名称。
编辑 2:我明白了:
Vocabulary vocabulary = lexer.getVocabulary();
lexer.reset();
for (Token token: lexer.getAllTokens()) {
System.out.println(token.getLine() + ":" + token.getCharPositionInLine() + " '" + token.getText() + "' " + vocabulary.getSymbolicName(token.getType()));
}
虽然这不是完全相同的功能,但仍然提供了主要信息!
英文:
In the terminal (or console), I can just do grun Exp eval -tokens
, but how do I do that from Java? I found that, that do like -tree
:
ParseTree tree = parser.eval();
System.out.println(tree.toStringTree(parser));
But I can't find anything similar for -tokens
.
Edit 1: I found something with lexer.reset()
:
lexer.reset();
for (Token token: lexer.getAllTokens()) {
System.out.println(token);
}
But the token are only numbers like <4>
, I would like to get the real name from it.
Edit 2: I got it:
Vocabulary vocabulary = lexer.getVocabulary();
lexer.reset();
for (Token token: lexer.getAllTokens()) {
System.out.println(token.getLine() + ":" + token.getCharPositionInLine() + " '" + token.getText() + "' " + vocabulary.getSymbolicName(token.getType()));
}
This isn't the exact same thing but the main infos still!
答案1
得分: 1
答案是:
Vocabulary vocabulary = lexer.getVocabulary();
lexer.reset();
for (Token token: lexer.getAllTokens()) {
System.out.println(token.getLine() + ":" + token.getCharPositionInLine() + " '" + token.getText() + "' " + vocabulary.getSymbolicName(token.getType()));
}
英文:
The answer is:
Vocabulary vocabulary = lexer.getVocabulary();
lexer.reset();
for (Token token: lexer.getAllTokens()) {
System.out.println(token.getLine() + ":" + token.getCharPositionInLine() + " '" + token.getText() + "' " + vocabulary.getSymbolicName(token.getType()));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论