Python - 只打印'打印'
问题描述:
我正在尝试制作自己的基本编程语言。我在我的smrlang.py
文件Python - 只打印'打印'
from sys import *
tokens = []
def open_file(filename):
data = open(filename, "r").read()
return data
def smr(filecontents):
tok = ""
state = 0
string = ""
filecontents = list(filecontents)
for char in filecontents:
tok += char
if tok == " ":
if state == 0:
tok = ""
else:
tok = " "
elif tok == "PRINT":
tokens.append("PRINT")
tok = ""
elif tok == "\"":
if state == 0:
state = 1
elif state == 1:
print("STRING")
string = ""
state = 0
elif state == 1:
string += tok
print(tokens)
def run():
data = open_file(argv[1])
smr(data)
run()
下面的代码,我有这个在我的one.smr
文件:
PRINT "HELLO WORLD"
输出应该是这样的PRINT STRING
,但是当我用命令python3 smrlang.py one.smr
,输出只是PRINT
。我使用Python 3
答
调试它的头,我发现这个问题:
elif state == 1:
string += tok
你不重置令牌这里。它将是aababcabcd
而不是abcd
并且识别\
将不起作用(因为它将是aababcabcd\
)。
这也导致令牌只是一切,它永远不会打印。
尝试将其更改为:修正后
elif state == 1:
string += tok
tok = ""
输出:
> py -3 temp.py temp.txt
STRING
['PRINT']
使用调试器或增加更多的调试print语句代码。 –