版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/84402790
一 实战——更复杂的用户输入
1 lexicon.py
def scan(sentence):
result = []
words=sentence.split()
length = len(words);
while words:
if words[0] in ['east','west','north','south']:
result.append(('direction',words[0]))
elif words[0] in ['go', 'kill', 'stop','eat']:
result.append(('verb',words[0]))
elif words[0] in ['door','bear','princess','cabinet']:
result.append(('noun',words[0]))
elif words[0] in['the','in','of','from','at','it']:
result.append(('stop',words[0]))
elif convert_number(words[0]):
num = int(words[0])
result.append(('number',num))
else:
result.append(('error',words[0]))
words = words[1:]
return result
def convert_number(s):
try:
return int(s)
except ValueError:
return None
2 lexicon_test.py
from nose.tools import *
from ex48 import lexicon
def test_directions():
assert_equal(lexicon.scan("north"), [('direction', 'north')])
result = lexicon.scan("north east south")
assert_equal(result, [('direction', 'north'),
('direction', 'east'),
('direction', 'south')])
def test_verbs():
assert_equal(lexicon.scan("go"), [('verb', 'go')])
result = lexicon.scan("go kill eat")
assert_equal(result, [('verb', 'go'),
('verb', 'kill'),
('verb', 'eat')])
def test_stops():
assert_equal(lexicon.scan("the"),[('stop', 'the')])
result = lexicon.scan("the in of")
assert_equal(result, [('stop', 'the'),
('stop', 'in'),
('stop', 'of')])
def test_nouns():
assert_equal(lexicon.scan("bear"), [('noun', 'bear')])
result = lexicon.scan("bear princess")
assert_equal(result, [('noun', 'bear'),
('noun', 'princess')])
def test_numbers():
assert_equal(lexicon.scan("1234"), [('number', 1234)])
result = lexicon.scan("3 91234")
assert_equal(result, [('number', 3),
('number', 91234)])
def test_errors():
assert_equal(lexicon.scan("ASFSDFASDF"),[('error','ASFSDFASDF')])
result = lexicon.scan("bear IAS princess")
assert_equal(result, [('noun', 'bear'),
('error', 'IAS'),
('noun', 'princess')])
二 测试结果
E:\Python\exercise\ex48\skeleton>nosetests
......
----------------------------------------------------------------------
Ran 6 tests in 0.035s
OK
E:\Python\exercise\ex48\skeleton>python
Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from ex48 import lexicon
>>> lexicon.scan("go north")
[('verb', 'go'), ('direction', 'north')]
>>> lexicon.scan("kill the princess")
[('verb', 'kill'), ('stop', 'the'), ('noun', 'princess')]
>>> lexicon.scan("eat the bear")
[('verb', 'eat'), ('stop', 'the'), ('noun', 'bear')]
>>> lexicon.scan("open the door and smack the bear in the nose")
[('error', 'open'), ('stop', 'the'), ('noun', 'door'), ('error', 'and'), ('error', 'smack'), ('stop', 'the'), ('noun', 'bear'), ('stop', 'in'), ('
stop', 'the'), ('error', 'nose')]