Python - 只打印'PRINT'

时间:2016-09-24 22:26:29

标签: python

我正在尝试制作自己的基本编程语言。我的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()

我在one.smr文件中有这个:

PRINT "HELLO WORLD"

输出应该类似于PRINT STRING,但是当我使用命令python3 smrlang.py one.smr时,输出只是PRINT。我正在使用Python 3

1 个答案:

答案 0 :(得分:0)

调试它的头部,我发现了问题:

elif state == 1:
    string += tok

您不在此处重置令牌。它将是aababcabcd而不是abcd,并且识别\将无效(因为它将是aababcabcd\)。

这也会导致令牌只是一切,而且永远不会打印。

尝试将其更改为:

elif state == 1:
    string += tok
    tok = ""

修复后的输出:

> py -3 temp.py temp.txt
STRING
['PRINT']