简体   繁体   English

字典映射不起作用python

[英]Dictionary mapping not working python

I am writing a lexer for my compiler.There is a function to map appropriate values when we input a token.But getting the error: 我正在为我的编译器编写一个词法分析器,当我们输入一个令牌时,有一个函数可以映射适当的值,但是出现错误:

[pylint] E0001:invalid syntax (, line 28) [pylint] E0001:语法无效(第28行)

Lexer.py Lexer.py

class Token(object):
    ILLEGAL_TOKEN = -1
    TOKEN_PLUS = 1
    TOKEN_MULT = 2
    TOKEN_DIV = 3
    TOKEN_SUB = 4
    TOKEN_OPEN_PAREN = 5
    TOKEN_CLOSE_PAREN = 6
    TOKEN_DOUBLE = 7
    TOKEN_NULL = 8

class Lexer(object):
    @classmethod
    def __init__(self, Expression):
        self.IExpression = Expression
        self.length = len(Expression)
        self.index = 0
        self.number = None
    @staticmethod
    def get_token(self):
        token = Token.ILLEGAL_TOKEN
        while self.index < self.length and (self.IExpression[self.index] == '' or self.IExpression[self.index] == '\t'):
            self.index += 1
        if self.index == self.length:
            return Token.TOKEN_NULL
        t = self.IExpression[self.index]

        switchCase = {
            '+' : token = Token.TOKEN_PLUS, self.index += 1,
            '-' : token = Token.TOKEN_SUB, self.index += 1,
            '*' : token = Token.TOKEN_MULT, self.index += 1,
            '/' : token = Token.TOKEN_DIV, self.index += 1,
            '(' : token = Token.TOKEN_OPEN_PAREN, self.index += 1,
            ')' : token = Token.TOKEN_CLOSE_PAREN, self.index += 1
        }
        return switchCase.get(t)

The value of a dictionary entry, like any value, has to be an expression which evaluates to a result (and the creators of Python made sure that you cannot assign and return a value at the same time). 字典条目的值与任何值一样,必须是一个计算结果的表达式(Python的创建者确保不能同时分配返回值)。 So assignment statements don't qualify. 因此,赋值语句不符合条件。

You could put a function (like a lambda or like in this Q&A: Python switch case ) as value and call it when you get it, but in your case there's a better & simpler equivalent solution: 您可以将一个函数(例如lambda或类似的问题,在此Q&A: Python switch case中 )设置为值,并在get它时调用它,但是在您的情况下,有一个更好,更简单的等效解决方案:

    switchCase = {
        '+' : Token.TOKEN_PLUS,
        '-' : Token.TOKEN_SUB,
        ...
    }
    token = switchCase.get(t)
    if token is not None:
       self.index += 1
    return token

So if the token is in the dict, you get your enumerate value and you can increase your index there (since you do it in all "cases" anyway) 因此,如果令牌包含在字典中,您将获得枚举值,并且可以在那里增加索引(因为无论如何在所有“情况下”都可以这样做)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM