我在 python 中创建了一个类,它将代码流拆分为令牌并逐个令牌推进令牌以与它们一起使用
import re
class Tokenizer:
def __init__(self, input_file):
self.in_file = input_file
self.tokens = []
self.current_token = None
self.next_token = None
self.line = 1
def split_tokens(self):
''' Create a list with all the tokens of the input file '''
self.tokens = re.findall("\w+|[{}()\[\].;,+\-*/&|<>=~\n]", self.in_file)
def __iter__(self):
for token in self.tokens:
if token != '\n':
yield token
else:
self.line += 1
def advance(self):
self.current_token = self.next_token
self.next_token = next(self.__iter__())
初始化后:
text = 'constructor SquareGame03 new()\n\
{let square=square;\n\
let direction=direction;\n\
return square;\n\
}'
t = Tokenizer(text)
t.split_tokens()
t.advance()
如果我打印令牌,它似乎有效
print(t.current_token, t.next_token)
None constructor
但是 advance 方法的每一次调用都会给出这些结果:
t.advance()
print(t.current_token, t.next_token)
constructor constructor
t.advance()
print(t.current_token, t.next_token)
constructor constructor
所以它没有进步,我不明白为什么。
呼啦一阵风
慕丝7291255
随时随地看视频慕课网APP
相关分类