direction =['north','south','east','west','down','up','left','right','back']
verb =['go','stop','kill','eat']
stop =['the','in','of','from','at','it','to']
noun =['door','bear','princess','cabinet']defscan(stuff):
words = stuff.split()# 通过指定分隔符对字符串进行切片,切片后为list
sentence =[]for word in words:print('words======',words)try:if word in direction:
sentence.append(('direction',word))#append 函数本身需要一个括号,值转换换要一个括号elif word in verb:
sentence.append(('verb',word))elif word in stop:
sentence.append(('stop',word))elif word in noun:
sentence.append(('noun',word))else:
word =int(word)
sentence.append(('number',word))except ValueError:
sentence.append(('error',word))return sentence
from nose.tools import*from Lexicon import*deftest_directions():
assert_equal(scan('north'),[('direction','north')])
result = scan('north south east')
assert_equal(result,[('direction','north'),('direction','south'),('direction','east')])deftest_verbs():
assert_equal(scan('go'),[('verb','go')])
result = scan('go kill eat')
assert_equal(result,[('verb','go'),('verb','kill'),('verb','eat')])deftest_stop():
assert_equal(scan('the'),[('stop','the')])
result = scan('the in of')
assert_equal(result,[('stop','the'),('stop','in'),('stop','of')])deftest_nouns():
assert_equal(scan('bear'),[('noun','bear')])
result = scan('bear princess')
assert_equal(result,[('noun','bear'),('noun','princess')])deftest_numbers():
assert_equal(scan('1234'),[('number',1234)])
result = scan('3 91234')
assert_equal(result,[('number',3),('number',91234)])deftest_errors():
assert_equal(scan('ASDFADFASDF'),[('error','ASDFADFASDF')])
result = scan('bear IAS princess')print('1',result)
assert_equal(result,[('noun','bear'),('error','IAS'),('noun','princess')])