在Python文件流中回退
我正在尝试写一个编译器,想要逐个字符地读取文件。如果我发现一个字符是"/",后面紧跟着另一个"/",那么我就想把这一行的其余部分当作注释来处理。我每次想要读取一个字符时,都是用file.read(1)。但是,如果我看到"/"后面跟着的不是"/",有没有办法让我把文件流回退一个字符,这样就不会丢失那个字符了呢?
def tokenType(self):
# PAGE 108
if (self.current == '{' or self.current == '}' or self.current == '(' or self.current == ')' or self.current == '[' or self.current == ']' or self.current == '.' or self.current == ',' or self.current == ';' or self.current == '-' or self.current == '*' or self.current == '/' or self.current == '&' or self.current == '|' or self.current == '<' or self.current == '>' or self.current == '=' or self.current == '~'):
if (self.current == '/'):
next = self.file.read(1)
if (next == '/'):
while (next != "\n"):
next = self.file.read(1)
return "IGNORE"
if (next == '*'):
while (True):
next = self.file.read(1)
if (next == '*'):
next = self.file.read(1)
if (next == '/'):
break
return "IGNORE"
else:
return "SYMBOL"
return "SYMBOL"
elif (self.current == " " or self.current == "\n"):
return "IGNORE"
elif (self.current == "'"):
while(next != "'"):
self.current = self.current + next
return "STRING_CONST"
elif (type(self.current) == int):
next = self.file.read(1)
while(next != " "):
self.current = self.current + next
return "INT_CONST"
else:
next = self.file.read(1)
while(next != " " and next != ""):
self.current = self.current + next
next = self.file.read(1)
if (self.current == 'class' or self.current == 'constructor' or self.current == 'function' or self.current == 'method' or self.current == 'field' or self.current == 'static' or self.current == 'var' or self.current == 'int' or self.current == 'char' or self.current == 'boolean' or self.current == 'void' or self.current == 'true' or self.current == 'false' or self.current == 'null' or self.current == 'this' or self.current == 'let' or self.current == 'do' or self.current == 'if' or self.current == 'else' or self.current == 'while' or self.current == 'return'):
return "KEYWORD"
else:
return "IDENTIFIER"
我的问题出现在像10/5这样的情况,当我的程序检查下一个字符是否是"/"时。然后在下一次调用我的字符解析函数时,数字5已经被移除了,因为它在检查注释的时候被处理掉了。
所以,有没有办法让我从文件流中获取一个字符,而不让它在流中“消失”,或者有没有办法让我在遇到这种情况时把流回退一个字符呢?
1 个回答
1
这方法看起来不太好,但如果你不介意把整个文件都读到内存里,你可以把当前符号和下一个符号传递给你的函数。你只需要找到一种方法来忽略下一个字符。
data = open('input_file').read()
for first, second in zip(data, data[1:]):
tokenType(first, second)
不过,就像roippi说的,还有更好的方法来处理输入。