經過半天的綢繆,敲擊,檢錯,修正,終於完成了第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工具測試結果如下: