Learn Python the hard way 習題48__Python

來源:互聯網
上載者:User
# 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的用法,點是子檔案夾













聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.