2014-10-04 30 views
0

我對Python很陌生,正在通過「Learn Python The Hard Way」Web教程學習。但是由於傳遞單個字符串時遇到問題,我停下了腳步。我能夠通過一個列表OK ...Python:列表迭代可以工作,但單個字符串不會

練習48讓我們對單元測試中的代碼進行反向工程。單元測試是:

def test_directions(): 
    assert_equal(Lexicon.scan("north"), [('direction', 'north')]) 

我的代碼如下所示:

class Lexicon: 

    def __init__(self): 
     self.directions = ['north','south','east','west','down','up','left','right','back'] 
     self.verbs = ['go','stop','kill','eat'] 
     self.stops = ['the','in','of','from','at','it'] 
     self.nouns = ['door','bear','princess','cabinet'] 

    def scan(self, words): 

     result = [] 

     for i in words: 
      if i in self.directions: 
       result.append(('direction', i)) 
      elif i in self.verbs: 
       result.append(('verb', i)) 
      elif i in self.stops: 
       result.append(('stop', i)) 
      elif i in self.nouns: 
       result.append(('noun', i)) 
      else: 
       try: 
        result.append(('number', int(i))) 
       except ValueError: 
        result.append(('error', i)) 


     return result 

運行從Python提示代碼給我下面的結果:

>>> from lexicon import Lexicon 
>>> test = Lexicon() 
>>> test.directions 
['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back'] 
>>> words = ['south'] 
>>> test.scan(words) 
[('direction', 'south')] 
>>> 
>>> test.scan("north") 
[('error', 'n'), ('error', 'o'), ('error', 'r'), ('error', 't'), ('error', 'h')] 
>>> 

,我會很感謝如果有人能指出爲什麼列表被單獨處理不同的字符串?還有我該如何重新編寫我的代碼,以便兩者的處理方式相同?

在此先感謝,奈傑爾。

+0

在第一種情況下,您傳遞了一個帶有單個元素的列表,而在第二種情況下,您傳遞的是字符串本身,這不是預期的輸入參數(因此是不需要的行爲)。 – 2014-10-04 15:09:24

+0

該練習中的'unittest'也顯示了由空格分隔的多個單詞的單個字符串參數 - 您將需要考慮您的方法中的單詞字符串參數。 – wwii 2014-10-04 16:24:48

回答

0
def scan(self, words): 

    result = [] 
    words = words.split() 

    for i in words: 
     ... 

演習的單元測試可以被看作是黑箱規範如何調用該方法。你的方法必須符合該規範。

要說明可能包含多個由空格分隔的單詞的字符串參數,split字符串。 split返回一個list,它將用於該方法的其餘部分。

+0

謝謝wwii!這很好用:>>> stuff = raw_input('>') > go north west tues 1 south >>> test.scan(stuff) [('verb','go'),('direction', 'north'),('direction','west'),('error','tues'),('number',1),('direction','south')] >>> test.scan (「北」) [('direction','north')] >>> – NDP 2014-10-04 20:27:20

1

該行正試圖通過文字

for i in words: 

的列表迭代如果你只是傳遞,i一個字符串實際上將在每一個字母,例如

for i in 'test': 
    print i 

t 
e 
s 
t 

要通過在一個單詞,通過長度爲1的list

test.scan(["north"]) 
0

您的功能不適用於單個字符串。會發生什麼是for i in words:重複字符串的字符

可以更改函數,使其可以同時處理單個字符串和字符串迭代。然而,總是通過iteratables而不用單個字符串會更加一致。

要傳遞一個字符串,只需傳遞一個元素列表(["north"])或元組(("north",))。

+0

謝謝NPE(和Cyber​​)。那麼,如上所述編寫單元測試是不正確的?什麼是滿足assert_equal測試的方法?輸入應該來自raw_input,然後split()會給出一個列表,所以單個字符串永遠不會以其本地形式傳遞... – NDP 2014-10-04 15:16:25

+0

@NDP - 單元測試應該/將描述*呼叫簽名*以確保unittest通過'''Lexicon.scan'''需要接受單個字符串。 – wwii 2014-10-04 16:19:28