经过半天的绸缪,敲击,检错,修正,终于完成了第48小节作者留的作业,虽然代码看起来很糟糕,但是收获不小,我是菜鸟,大神勿喷啊,嘎嘎嘎
#encoding:utf-8
import re
def scan(sentence = None):
directions = ['north','south','east','west']
verbs = ['go','kill','eat']
stops = ['the','in','of']
nouns = ['bear','princess']
reward = []
global EN
if sentence == None: # 如果是***不传参***,就请求输入
command = raw_input("Please input your command > ")
while command == '': # 如果输入***为空***,就再次请求
command = raw_input("Please input your command > ")
else: # 如果是***传参***,就用参数作为输入
command = sentence
words = command.split() # 将句子分离为单词序列
r1 = r"^[0-9]+$" # 纯数字的正则表达式
for word in words:
if re.match(r1,word) != None:# 判断是否能够匹配
word = int(word)
if type(word) == str : # 判断单词是否为***字符串***类型
for direction in directions: # 判断单词是否在***方向***列表内
if direction == word:
reward.append(('direction', word))
EN = True
break
else:
EN = False
if EN == True:
continue
for verb in verbs: # 判断单词是否在***动词***列表内
if verb == word:
reward.append(('verb', word))
EN = True
break
else:
EN = False
if EN == True:
continue
for stop in stops: # 判断单词是否在***顿词***列表内
if stop == word:
reward.append(('stop', word))
EN = True
break
else:
EN = False
if EN == True:
continue
for noun in nouns: # 判断单词是否在***名词***列表内
if noun == word:
reward.append(('noun', word))
EN = True
break
else:
EN = False
if EN == False:
reward.append(('error', word))
elif (type(word) == int )or(type(word) == float)\
or(type(word) == long )or(type(word) == complex):
reward.append(('number', word))
else:
reward.append(('error', word))
break
return reward
用nose工具测试结果如下: