Python:AssertionError
首先,这是我需要测试的代码:Python:AssertionError,python,python-2.7,Python,Python 2.7,首先,这是我需要测试的代码: 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_li
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)
我输入的列表是[(‘动词’、‘味道’)、(‘方向’、‘好’)、(‘名词’、‘比萨饼’)]
这个列表中的第一个值是('verb','taste'),它的单词类型是'verb',它符合我在编码中给出的单词类型,但我得到了错误
断言者错误:无!='动词'
我认为这是不合理的
def test_skip():
skipA = skip([('verb','taste'),('direction','good'),('noun','pizza')], 'verb')
assert_equal(skipA, 'verb')
# assert_equal(skipA, None)
函数
skip
不返回任何值(这意味着它返回None
)
因此,
skipA
是None
,断言失败。使用“skip”方法可能会出现问题,因为“skip”不返回任何表示“skip”返回None的值。您需要在skip函数中返回一个值。您返回的是peek and match,但是调用skip并希望从中获取值的范围意味着您也需要返回 但是我在match中写了“if word[0]==expecting:return word”,所以我认为它应该返回word@Electro01你从match
返回,但你不是从skip
返回,但我还是有点困惑,因为我认为在函数skip的末尾,它调用match,因此可能会返回vauleIt,它在循环中调用match,但不返回任何内容