# coding:utf-8 class lexicon(object):def __init__(self):# dictionary to find word onself.directions = ['south', 'north', 'east', 'west']self.verbs = ['go', 'kill', 'eat']self.stops = ['the', 'in', 'of']self.nouns = ['bear', 'princess']def scan(self, sentence):result = []words = sentence.split()## while(len(words) != 0):#word = words.pop(0)for word in words:##if(self.direction.count(word) == 1):if word in self.directions:result.append(('direction', word))elif word in self.verbs:result.append(('verb', word))elif word in self.stops:result.append(('stop', word))elif word in self.nouns:result.append(('noun', word))else:try:word = int(word)result.append(('number', word))except ValueError:result.append(('error', word))return result# 測試未執行個體化 否則會unboundlexicon = lexicon()
練習48是第一次自己寫代碼,出現了很多問題。
1.unboud:習題的測試代碼沒有執行個體化lexicon,需要在模組中執行個體化。
2.關於怎麼在列表中尋找是否存在:
自己寫成這樣:
if(self.direction.count(word) == 1):
後來看到別人的代碼:
if word in self.directions:
就可以了,,,
3.迴圈的條件:
也是:
while(len(words) != 0):
word = words.pop(0)
這樣就行(還不用定義word了:
for word in words:
不過學到了不少list的方法。
還有的疑問:
書上是:from ex48 import lexicon
而我:from Game.lexicon import lexicon。 不加'.lexicon'就會importError
查詢import的用法,點是子檔案夾