my_table={"begin":1,"if":2,"then":3,"while":4,"do":5,
"end":6,"+":13,"-":14,"*":15,"/":16,":":17,
":=":18,"<":20,"<>":21,"<=":22,">":23,">=":24,
"=":25,";":26,"(":27,")":28,"#":0}
def scanner():
global my_table
key_list=list(my_table.keys())
init_state=input("input a string\n")
i=0
while i < len(init_state):
flag=1
while init_state[i].isspace():
i+=1
if init_state[i].isalpha():#标识符及关键字逻辑
token=""
while i<len(init_state) and init_state[i].isalnum():
token+=init_state[i]
i+=1
if token not in key_list:#判定为关键字
print("(10,"+token+")")
else:
print("("+str(my_table[token])+","+token+")")#判定为标识符
flag=0
continue
if init_state[i].isdigit():#整型常数逻辑
token=""
while i<len(init_state) and init_state[i].isdigit():
token+=init_state[i]
i+=1
print("(11,"+token+")")
flag=0
continue
if init_state[i] in key_list:#运算符及符号逻辑
if i+1<len(init_state) and (init_state[i]+init_state[i+1]) in key_list :
print("("+str(my_table[init_state[i]+init_state[i+1]])+","+init_state[i]+init_state[i+1]+")")
i+=2
else:
print("("+str(my_table[init_state[i]])+","+init_state[i]+")")
i+=1
flag=0
continue
if flag:
print(init_state[i]+" can not parse")
i+=1
scanner()
词法分析程序
最新推荐文章于 2016-04-23 01:15:00 发布