2013-05-20 33 views
0
direction = ['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back'] 
class Lexicon(object): 

    def scan(self, sentence): 
     self.sentence = sentence 
     self.words = self.sentence.split() 
     self.term = [] 

     for word in self.words: 
      if word in direction: 
       part = ('direction','%s' % word) 
       self.term.append(word) 
      return self.term 


lexicon = Lexicon() 

當我通過lexicon.scan('north south east')我期待回報給我[('direction','north'),('direction','south'),('direction','east')]。相反,我得到['north']。這是我希望程序在整體上做的事情。爲什麼我的代碼不能正確創建元組列表?

  1. 拿一句話。
  2. 使用對該句子的掃描並將句子分成不同的單詞。
  3. 掃描檢查了幾個列表中的所有單詞(這只是單個列表中的第一個測試)。
  4. 如果在一個列表中找到一個單詞,那麼我想創建一個元組,其中第一個單詞是列表的名稱,第二個單詞是單詞。
  5. 我想爲不在列表中的單詞創建一個元組,就像之前一樣,但使用「錯誤」而不是列表名稱。
  6. 我想在元組
+0

FWIW,我會在那裏放置一個'方向=設置(方向)'的效率。 – mgilson

+2

你確定句子,單詞和術語需要是實例變量嗎?如果不需要存儲,最好使用局部變量。 –

回答

5

此:

self.term.append(word) 

應該是這樣的:

self.term.append(part) 

你丟棄part,而不是將它添加到self.term

此外,你從0123循環內而不是循環之後 - 你需要將你的return聲明縮進一個檔次。這裏的工作代碼:

for word in self.words: 
    if word in direction: 
     part = ('direction','%s' % word) 
     self.term.append(part) 
return self.term 

輸出:

[('direction', 'north'), ('direction', 'south'), ('direction', 'east')] 
4

這條線在這裏的第一部分返回記錄稱爲術語,它擁有所有的在它的不同單詞的列表,與他們的列表名稱或錯誤太遠縮進在:

return self.term 

這是for循環體的一部分,所以你的循環返回過早。把它放下一個縮進級別。

您也可以使用列表理解:

self.term = [('direction', word) for word in self.words if word in direction] 
0

我想補充的其他答案的頂部,這不是讓兩個集合的交集的最佳途徑。爲什麼不簡單使用Python sets

class Lexicon(object): 

     def bar(self, sentence): 
      return set(sentence.split()) & set(direction) 

我覺得這個既清晰又高效。

相關問題