首先,這是我需要的測試代碼:的Python:Asse田
class ParserError(Exception):
pass
class Sentence(object):
def __init__(self, subject, verb, object):
self.subject = subject [1]
self.verb = verb[1]
self.object = object[1]
def peek(word_list):
if word_list:
word = word_list[0]
return word[0]
else:
return None
def match(word_list, expecting):
if word_list:
word = word_list.pop(0)
if word[0] == expecting:
return word
else:
return None
else:
return None
def skip (word_list, word_type):
while peek(word_list) == word_type:
match(word_list, word_type)
def parse_verb(word_list):
skip(word_list, 'stop')
if peek(word_list) == 'verb':
return match(word_list, 'verb')
else:
raise ParserError("Expected a verb next.")
def parse_object(word_list):
skip(word_list,'stop')
next = peek(word_list)
if next == 'noun':
return match(word_list, 'noun')
if next == 'direction':
return match(word_list, 'direction')
else:
raise ParserError('Expected a noun or direction next.')
def parse_subject(word_list, subj):
verb = parse_verb(word_list)
obj = parse_object(word_list)
return Sentence(subj, verb, obj) # 執行 class Sentence
def parse_sentence(word_list):
skip(word_list, 'stop')
start = peek(word_list)
if start == 'noun':
subj = match(word_list, 'noun')
return parse_sentence(word_list, subj)
elif start == 'verb':
# assume the subject is the player then
return parse_subject(word_list, ('noun', 'player'))
else:
raise ParserError("Must start with subject, object, or verb not: %s" % start)
我是[( '動詞', '品味')類型的列表,( '方向', '好'), ('noun','pizza')] 這個列表中的第一個值是('動詞','品味'),它的word_type是'動詞',它適合我在編碼中給出的word_type,但是我得到錯誤 AssertionError:無!='動詞' 我認爲這是不合理的。
def test_skip():
skipA = skip([('verb','taste'),('direction','good'),('noun','pizza')], 'verb')
assert_equal(skipA, 'verb')
# assert_equal(skipA, None)
但我寫的「如果字[0] ==預期: 反饋字」的比賽,所以我認爲它應該返回@ Electro01你'match'返回字 – Electro01
,但你不從返回'skip' – alfasin
但我仍然有點困惑因爲我認爲在函數跳過的結尾,它調用匹配,所以它可能會返回價值 – Electro01