0

如前所述,我确信这是一个简单的错误让我开始面对,但我无法弄清楚为什么我的变量 newState 在显式设置为字符串“F1”时不会触发以下条件的 else 条件:如果 newState == 'F1'...

我想我不需要移植这么多代码,抱歉。

 (EOL, LETTER, DIGIT, PERIOD, ILLEGAL_CHAR, LEGAL_CHAR) = range(0, 6)


STT = [ ['error', 1, 2, 0, 'error', 0], ['F1', 1, 1, 'F1', 'error', 'F1' ], 
['F2', 'F2', 2, 3, 'error', 'F2'], ['error', 'error', 4, 'error', 'error', 'error'],
['F3', 'F3', 4, 'F3', 'error', 'F3']  ]

for line in open("Sample.txt","r"):
    x1 = ''
    currState = 0
    newState = 'F1'
    for char in line:
        if newState != 'F1' or newState != 'F2' or newState != 'F3' or newState != 'error':
            currState = newState
            #If eol
            if char == '\n':
                response = EOL
                newState = STT[currState][response]
                break
            #if letter
            elif char.isalpha():
                x1 = x1 + char
                response = LETTER
                newState = STT[currState][response]
               # break
            #if Digit
            elif char.isdigit():
                x1 = x1 + char
                response = DIGIT
                newState = STT[currState][response]
            #if Period
            elif char == '.':
                x1 = x1 + char
                response = PERIOD
                newState = STT[currState][response]                       
            #If illegal char set
            elif (char == '~' or char == '?' or char == ':' or char == '_' or char == '\\' ):
                response = ILLEGAL_CHAR
                newState = STT[currState][response]
                break
                                           # elif x1 != '':  
                                                #response = 5
                                               # newState = STT[currState][response]
                                               # break
            #if any other legal char
            else:
                response = LEGAL_CHAR
                newState = STT[currState][response]        
        #We have a token
        else:
            getToken(newState, x1)
4

1 回答 1

3

ifnewstate是F1,不会触发else,因为newState != 'F2'会触发。

在第一个 if 中,尝试制作它

if (not(newState == 'F1' or newState == 'F2' or newState == 'F3' or newState == 'error')):

问题是

if !A or !B or ...

不一样

if !(A or B or...)

这等于

if (!A and !B and ...)

根据德摩根斯定律。

于 2013-11-04T02:12:22.940 回答