这一节主要是对用户输入的词汇进行识别。
这是我写的扫描器:
direction = ('north', 'south', 'east', 'west',
'down', 'up', 'left', 'right', 'back')
verb = ('go', 'stop', 'kill', 'eat')
stops = ('the', 'in', 'of', 'from', 'at', 'it')
noun = ('door', 'bear', 'princess', 'cabinet')
alword = dict([(i, 'direction') for i in direction]+
[(i, 'verb') for i in verb]+
[(i, 'stops') for i in stops]+
[(i, 'noun') for i in noun])
def scan(input):
x = input.split()
res = []
for i in x:
if i in alword:
res.append((alword[i],i))
else:
try:
num = int(i)
except ValueError:
res.append(('error',i))
else:
res.append(('number',num))
return res
将数据及对应关系存入字典,可以极大地减少代码量,但相对存储的数据量也变多了。
这是单元测试:
from nose.tools import *
from ex48 import lexicon
def test_directions():
assert_equal(lexicon.scan("north"), [('direction', 'north')])
result = lexicon.scan("north south east")
assert_equal(result, [('direction', 'north'),
('direction', 'south'),
('direction', 'east')])
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"), [('stops', 'the')])
result = lexicon.scan("the in of")
assert_equal(result, [('stops', 'the'),
('stops', 'in'),
('stops', '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_nouns():
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("ASDFADFASDF"),[('error', 'ASDFADFASDF')])
result = lexicon.scan("bear IAS princess")
assert_equal(result, [('noun', 'bear'),
('error', 'IAS'),
('noun', 'princess')])