词法分析器

时间:2018-12-14 02:34:25

标签: python compiler-construction

我的工作是为后缀表达式编写一个非常简单的词法分析器:

print ("enter each variable followed by a space" );
numbers = input("Enter the numbers: ") #ask for input

numbersArray = [] #array to store the input

for number in numbers:
    numbersArray.append(number)

numbersArray = numbersArray[::2]

print(numbersArray);

for x in numbersArray:

    if x == "_": print ( "     " , " delimeter" )
    elif x == "-": print ( "    ", " subtraction opp." )
    elif x == "/": print ( "    ", " divison opp." )
    elif x == "+": print ( "    ", " addition opp." )
    elif x == "*": print ( "    ", " multplication opp." )
    elif x == "0": print ( "    ", " Constant: 0 " )
    elif x == "1": print ( "    ", " Constant: 1" )
    elif x == "2": print ( "    ", " Constant: 2" )
    elif x == "3": print ( "    ", " Constant: 3" )
    elif x == "4": print ( "    ", " Constant: 4" )
    elif x == "5": print ( "    ", " Constant: 5" )
    elif x == "6": print ( "    ", " Constant: 6" )
    elif x == "7": print ( "    ", " Constant: 7" )
    elif x == "8": print ( "    ", " Constant: 8" )
    elif x == "9": print ( "    ", " Constant: 9" )
    elif x == "10": print ( "    ", " Constant: 10" )
    print(x) 

一个示例输入:3 _ 4 _ 5 _ +

以上是ive开始的内容,这是我第一次使用python,而ive一直在为此苦苦挣扎。我想知道是否有更好的方法可以将较大的数字和字母分别表示为常量和变量?

1 个答案:

答案 0 :(得分:0)

我同意评论者的观点,即使用ply之类的词法库是最简单或最佳的方法。如果您仍然想/需要自己做,则有几件事需要更改。

如果看到类似132的内容,则需要跳到下一个循环迭代的数字,因此for x in numbersArray:不起作用。您可以只执行while True,手动跟踪循环索引,然后在完成后退出。

使输入与词素匹配最有效的方法是使用regular expressions。例如,您可以使用类似

的形式将数字与可选的小数部分匹配
import re
...
re.match(r'\d+(\.\d*)?', numbersArray[current_index:])

(大多数数字规范都比这更“有趣”,因此绝对不要复制我的正则表达式。对于您所需要的东西可能是错误的。)

您可以使用regex101.com进行实验并构建正则表达式。

您也可以使用string methods内置的Python,例如isnumericisalpha。这样,您的号码检查可能看起来像

lexeme = ''
while numbersArray[current_index].isdigit():
    lexeme += numbersArray[current_index]
    current_index += 1