自上而下语法分析器python

良心创作,鏖战一整天






#分析表M
dicM={
    "S":{"(":"A", ")":"A"},
    "A":{"(":"CB", ")":"CB" },
    "B":{"i":"iCB","*":"e", "$":"e"},
    "C":{"(":"ED", ")":"ED" },
    "D":{"i":"e","+":"+ED","*":"e", "$":"e"},
    "E":{"(":"(", ")":")A*" }
}

#非终结符
VN=[]
for item in dicM.keys():
    VN.append(item);
print("非终结符VN集合为:{0}".format(VN))

#终结符
VT=[]
# print(len(dicM))
for item in dicM.values():
    for it in item:#遍历key值
        VT.append(it)
VT=list(set(VT))
VT.append("e")
print("终结符VT集合为{0}:".format(VT))

#翻转字符串,返回字符串
def convertStr(arg):
    conarg=arg[::-1]
    return conarg

#找产生式,返回产生式右部
def findCSS(argS,argstr):
    if argS in dicM.keys() :
        temp_value=dicM[argS]
        if argstr in temp_value.keys():
            temp=temp_value[argstr]
            return temp
    return ""
#截取列表 除去最后一个元素
def substr(arg):
    # print(arg,"fdsfs")
    Listarg=list(arg)
    le=len(Listarg)
    args=Listarg[0:le-1]
    return args

def addS(arg,args):
    Listargs=list(args)
    for i in arg:
        Listargs.append(i)
    return  Listargs

strString=input("请输入要分析的符号串:")#输入串
# strString="(i("
str=list(strString)
str.append("$")

COUNT=0#步骤

#符号栈
S=["$"]
S.append(VN[0])
# print(S)
CSRight=""
print("步骤\t符号栈S[i]\t\t\t输入串str[j]\t\t\t产生式")
while len(S)!=0:
    COUNT += 1
    ch = str[0]
    CSRight0 = findCSS(S[-1], str[0])
    if CSRight0!="" and S[-1] not in VT:
        print("%s\t%s\t\t\t\t%s\t\t\t\t%s" % ( COUNT, "".join(S).center(10), "".join(str).center(10),S[-1] + "->" +CSRight0))
    elif  CSRight0 in VT or S[-1]  in VT:
        print("%s\t%s\t\t\t\t%s" % ( COUNT, "".join(S).center(10), "".join(str).center(10)))
    elif CSRight0=="":
        print("\033[0;31m%s\033[0m" % "该句子不是该文法!")
        break
    CHS = S.pop()
    CSRight = findCSS(CHS, str[0])
    if CHS not in VT  :#如果栈顶元素不是终结字符
        if CSRight!="":
            if CSRight[0] in VN :
                temp = convertStr(CSRight)
                S = addS(temp,S)
            elif CSRight[0] in VT and CSRight[0]!="e":
                temp = convertStr(CSRight)
                S = addS(temp, S)
            elif CSRight[0]=="e" and CSRight[0] in VT:
                pass
        elif CSRight=="":
            pass
    elif CHS in VT:
        if ch==CHS:
            if CHS=="$":
                # print("该句子属于该文法!")
                print("\033[1;31;40m该句子属于该文法!\033[0m")
            elif CHS!="$":
                str = str[1:]
        elif ch!=CHS:
            if CHS=="$":
                print("\033[0;31m%s\033[0m" % "该句子不是该文法!")
                pass







你可能感兴趣的:(python学习笔记)