def advance(self): """Advance the 'pos' pointer and set the 'current_char' variable.""" self.pos += 1 if self.pos > len(self.text) - 1: self.current_char = None # Indicates end of input else: self.current_char = self.text[self.pos]
def skip_whitespace(self): while self.current_char is not None and self.current_char.isspace(): self.advance()
def integer(self): """Return a (multidigit) integer consumed from the input.""" result = '' while self.current_char is not None and self.current_char.isdigit(): result += self.current_char self.advance() return int(result)
def get_next_token(self): """Lexical analyzer (also known as scanner or tokenizer)
This method is responsible for breaking a sentence apart into tokens. """ while self.current_char is not None:
if self.current_char.isspace(): self.skip_whitespace() continue
if self.current_char.isdigit(): return Token(INTEGER, self.integer())
if self.current_char == '+': self.advance() return Token(PLUS, '+')
if self.current_char == '-': self.advance() return Token(MINUS, '-')
# 这时要么是成功地找到 INTEGER PLUS INTEGER,要么是 INTEGER MINUS INTEGER # 序列的标记,并且这个方法可以仅仅返回两个整数的加或减的结果,就能高效解释客户端的输入 if op.type == PLUS: result = left.value + right.value else: result = left.value - right.value return result
def main(): while True: try: # To run under Python3 replace 'raw_input' call # with 'input' text = raw_input('calc> ') except EOFError: break if not text: continue interpreter = Interpreter(text) result = interpreter.expr() print(result)