词法分析程序

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值