2016-09-24 238 views
-1

我正在嘗試製作自己的基本編程語言。我在我的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

+0

使用調試器或增加更多的調試print語句代碼。 –

回答

0

調試它的頭,我發現這個問題:

elif state == 1: 
    string += tok 

你不重置令牌這裏。它將是aababcabcd而不是abcd並且識別\將不起作用(因爲它將是aababcabcd\)。

這也導致令牌只是一切,它永遠不會打印。

嘗試將其更改爲:修正後

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

輸出:

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