这段代码实现了一个简单的词法分析器,用于将输入的语句分解为一个个的单词(token),并输出每个单词的类型和值。该词法分析器支持的单词类型包括:标识符(var)、数字(int)、结束标记(#)、运算符(=,+,-,*,/,(,))。

该词法分析器的实现过程如下:

  1. 定义关键字表KW,其中包含了所有的关键字及其对应的标识符。

  2. 读入输入语句,并设置初始索引index=0。

  3. 检查输入语句是否以#结尾,若是则继续执行,否则输出错误信息并结束程序。

  4. 进入循环,遍历输入语句中的每个字符。

  5. 若该字符为字母,则记录下该字符,并查看下一个字符是否也为字母,若是则将其加入到当前记录的字符中,直到遇到一个非字母字符为止。然后根据当前记录的字符是否在关键字表KW中出现过,输出对应的标识符类型和值,或者输出标识符类型为1(表示为普通标识符)。

  6. 若该字符为空格,则跳过所有连续的空格。

  7. 若该字符为运算符,则输出对应的标识符类型和值。

  8. 若该字符为数字,则记录下该数字,并查看下一个字符是否也为数字,若是则将其加入到当前记录的数字中,直到遇到一个非数字字符为止。然后输出数字类型为2(表示数值型)和当前记录的数字值。

  9. 若该字符为#,则输出结束标记类型和值,并结束循环。

  10. 循环结束后,输出结束标记类型和值。

总的来说,该词法分析器的实现比较简单,只支持了基本的单词类型,没有对输入语句进行任何语法检查。在实际应用中,需要根据具体的需求来扩展词法分析器的功能,例如支持更多的单词类型、实现更复杂的语法检查等。

KW = {'var': 1, 'int': 2, '#': 3, '=': 4, '+': 5, '-': 6, '*': 7, '/': 8, '(': 9, ')': 10}
#var=>标识符 int=>数字 #=>结束标记
words = input('输入语句:')
index = 0
flag = 1
if(words[-1] != '#'):
    print('error:输入表达式应以#结尾!')
    flag = 0
while(index+1 < len(words) and flag == 1):
    ch = words[index]
    if(ord(ch) in range(ord('a'), ord('z')+1) or ord(ch) in range(ord('A'), ord('Z')+1)):
        #该字符为字母
        Crs = ch
        if(ord(words[index+1]) not in range(ord('a'), ord('z')+1) and ord(words[index+1]) not in range(ord('A'), ord('Z')+1)):
            if(Crs in KW.keys()):
                print('({},'{}')'.format(KW[Crs], Crs))
                index += 1
            else:
                print('({},'{}')'.format(1, Crs))
                index += 1
        else:
            while(ord(words[index+1]) in range(ord('a'), ord('z')+1) or ord(words[index+1]) in range(ord('A'), ord('Z')+1)):
                Crs = Crs + words[index+1]
                index += 1
                if(words[index+1] == '#' or ord(words[index+1]) not in range(ord('a'), ord('z')+1) and ord(words[index+1]) not in range(ord('A'), ord('Z')+1)):
                    if(Crs in KW.keys()):
                        print('({},'{}')'.format(KW[Crs], Crs))
                        index += 1
                        break
                    else:
                        print('({},'{}')'.format(1, Crs))
                        index += 1
                        break
    elif(ch == ' '):
        #该字符为空格
        while(words[index+1] == ' '):
            index += 1
        index += 1
    elif(ch in ['=', '+', '-', '*', '/', '(', ')']):
        #该字符为运算符
        index += 1
        print('({},'{}')'.format(KW[ch], ch))
    elif(ch in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']):
        #该字符为数字
        num = ch
        while(words[index+1] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']):
            num = num + words[index+1]
            index += 1
        index += 1
        print('({},{})'.format(2, num))
    if(words[index] == '#'):
        print('(3,'#')')
        break
Python 词法分析器实现 - 将语句分解为单词

原文地址: https://www.cveoy.top/t/topic/noL0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录