Python3 Antlr4 AttributeError:“CommonToken”对象没有属性“getLine”

2024-09-29 23:18:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Antlr4和Python3。在

我有一个getTerminalPos方法,它返回给定终端的行和列号的元组。为此,我首先使用.getSymbol()获取令牌,然后使用.getLine()和{}方法来获取位置。在

def getTerminalPos(self, terminal):
  token = terminal.getSymbol()
  return (token.getLine(), token.getCharPositionInLine())

在antlr访问者中调用getTerminalPos的示例:

^{pr2}$

运行代码时,收到以下错误消息:

  File ".../py-antlr4-lmaspl/AntlrVisitor.py", line 55, in getTerminalPos
    return (token.getLine(), token.getCharPositionInLine())
AttributeError: 'CommonToken' object has no attribute 'getLine'

根据antlr4java运行时,存在以下方法:https://www.antlr.org/api/Java/org/antlr/v4/runtime/CommonToken.html

根据antlr3python运行时,存在以下方法:https://www.antlr3.org/api/Python/classantlr3_1_1_common_token.html

那么,它们也应该存在于antlr4python运行时?在

如何修复此错误?我是否应该使用不同的方法来获取行号和列号?在

编辑:我的意思是我在这里发现了一个类似的问题:https://github.com/antlr/antlr4/issues/1529。它被标记为bug,但暂时关闭。。。在


Tags: 方法pyhttpsorgtokenreturn错误terminal
1条回答
网友
1楼 · 发布于 2024-09-29 23:18:27

如果我查看python3运行时的源代码,就会看到^{} like this

class CommonToken(Token):

    # An empty {@link Pair} which is used as the default value of
    # {@link #source} for tokens that do not have a source.
    EMPTY_SOURCE = (None, None)

    def __init__(self, source = EMPTY_SOURCE, type = None, channel=Token.DEFAULT_CHANNEL, start=-1, stop=-1):
        super(CommonToken, self).__init__()
        self.source = source
        self.type = type
        self.channel = channel
        self.start = start
        self.stop = stop
        self.tokenIndex = -1
        if source[0] is not None:
            self.line = source[0].line
            self.column = source[0].column
        else:
            self.column = -1

    ...

像这样Token

^{pr2}$

所以,我想这应该对你有用:

return (token.line, token.column)

相关问题 更多 >

    热门问题