首先,那是我需要测试的代码:
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)
我输入的列表是[('动词','品味'),('方向','好'), ('名词''比萨&#39)] 这个列表中的第一个值是('动词',#39;味道'),它的word_type是'动词',它适合我在编码中给出的word_type但是我收到了错误 断言错误:无!='动词' 我认为这是不合理的。
def test_skip():
skipA = skip([('verb','taste'),('direction','good'),('noun','pizza')], 'verb')
assert_equal(skipA, 'verb')
# assert_equal(skipA, None)
答案 0 :(得分:1)
函数skip
不返回任何值(这意味着它返回None
)。
所以skipA
是None
,断言失败。
答案 1 :(得分:0)
可能存在问题'跳过'方法,因为'跳过'没有返回任何意味着跳过'返回无
答案 2 :(得分:0)
您需要在跳过功能中返回。你在偷看和匹配中返回,但是你调用skip并从那里想要一个值的范围意味着你也需要返回那里。