[英]Python - Only printing 'PRINT'
I am trying to make my own basic programming language.我正在尝试制作自己的基本编程语言。 I have the following code in my smrlang.py
file我的smrlang.py
文件中有以下代码
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()
And I have this in my one.smr
file:我的one.smr
文件中有这个:
PRINT "HELLO WORLD"
The output should be something like PRINT STRING
, but when I use the command python3 smrlang.py one.smr
, the output is just PRINT
.输出应该类似于PRINT STRING
,但是当我使用命令python3 smrlang.py one.smr
,输出只是PRINT
。 I am using Python 3我正在使用 Python 3
Debugging it in the head, I found the problem:头部调试,发现问题:
elif state == 1:
string += tok
You don't reset the token here.您不要在此处重置令牌。 It will be aababcabcd
instead of abcd
and recognizing \\
won't work (as it will be aababcabcd\\
).它将是aababcabcd
而不是abcd
并且识别\\
将不起作用(因为它将是aababcabcd\\
)。
This also causes the token to just be everything and it will never print.这也导致令牌只是一切,永远不会打印。
Try changing it to:尝试将其更改为:
elif state == 1:
string += tok
tok = ""
Output after fix:修复后输出:
> py -3 temp.py temp.txt
STRING
['PRINT']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.