2011-07-30 104 views
3

我正在學習Python學習困難的方法,並且練習48已經遇到了一個難題。你被賦予了大量的代碼作爲單元測試,並要求我們按順序創建一個函數使單元測試通過。我不確定這段代碼應該是什麼樣子。我已經粘貼了其中一個函數作爲參考。他們都看起來很像這個,我確信如果我明白如何讓這一次通過,我可以找出其餘的。多謝你們!學習Python的難題練習48幫助

from nose.tools import * 
from ex48 import lexicon 


def test_directions(): 
    assert_equal(lexicon.scan("north"), [('direction', 'north')]) 
    result = lexicon.scan("north south east") 
    assert_equal(result, [('direction', 'north'), 
         ('direction', 'south'), 
         ('direction', 'east')]) 

回答

6
class lexicon: 
    @staticmethod 
    def scan(s): 
     return [('direction',x) for x in s.split()] 

print(lexicon.scan("north south east")) 
+0

非常感謝!快速的問題,因爲我在這個東西還是新的。這會返回給它作爲一個元組的句子嗎?這被認爲是該功能的目的。從這本書中:「這個掃描器將從用戶處接收一串原始輸入,並返回一個由(TOKEN,WORD)配對組成的列表組成的句子。如果一個單詞不是詞典的一部分,那麼它應該仍然返回WORD,但將TOKEN設置爲錯誤令牌,這些錯誤令牌會告訴用戶他們搞砸了。「 – Adam

+0

好吧,打印它,你會看到它返回的 - 元組列表。 –

+0

哦對。現在它給了我各種麻煩。看來測試程序不能導入代碼。我一直收到如下錯誤消息:ImportError:無法導入名詞詞典或無模塊名爲lexicon或NameError:全局名稱'詞典'沒有定義 – Adam

2

這裏是我的穴居人的Python的解決方案:

def scan(data): 
    data = data.split() 
    results = [] 

    for l in data: 
     if l in directions: 
      results.append(('direction', l)) 
     elif l in verbs: 
      results.append(('verb', l)) 
     elif l in stop_words: 
      results.append(('stop', l)) 
     elif l in nouns: 
      results.append(('noun', l)) 
     elif convert_number(l) in numbers: 
      results.append(('number', convert_number(l))) 
     else: 
      results.append(('error', l)) 

    return results 
0

這是一個完整的解決方案在學習練習48 Python的堅硬方式

directions = ['north', 'south', 'east'] 
stops =["the" , "in" , "of"] 
verbs = ['go','stop','kill','eat' ] 
numbers = xrange(999999999) 
nouns=["bear" , "princess" ] 
list_of_lists=['go','stop','kill','eat','north', 'south', 'east','door',"the" , "in" , "of","bear" , "princess",xrange(999999999)] 
list99=[] 


class lexicon: 
    @staticmethod 
    def scan(d): 
     list2=d.split() 
     list1=[] 
     list3=[] 
     try: 
      for x in d.split(): 

       if int(x) in xrange(999999999): 
        a = x 

        list1.append(a) 
        list2.remove(a) 
       else: 
        print "yes" 
     except: 
      list99=[] 

     for x in d.split(): 
      #print x 
      if x in nouns: 
       z1 = ("noun" , x) 
       list3.append(z1) 

      elif x in directions: 
       z2 = ("direction" , x) 
       list3.append(z2) 

      elif x in verbs: 
       z2 = ("verb" , x) 
       list3.append(z2) 
      elif x in list1: 
       z2 = ("number" , int(x)) 
       list3.append(z2) 
      elif x in stops: 
       z2 = ("stop" , x) 
       list3.append(z2) 
      elif x in list2: 
       z2 = ("error" , x) 
       list3.append(z2) 
      else: 
       print "yes" 

     print "d:%s"%d.split() 
     print "list1:%s"%list1 
     print "list2:%s"%list2 
     print "list3:%s"%list3 
     return list3 
0

我也是通過這個工作鍛鍊,我花了幾天時間才弄清楚(至少我認爲是對的)。 在編程方面,我是一個完整的noob,我想分享我的解決方案,從你們那裏得到關於它是否完成工作的反饋。 在此先感謝您的幫助!

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

def scan(sentence): 
    split_sentence = sentence.split() 
    # print split_sentence 
    list1 = [] 
    list2 = [] 
    length_of_list = len(split_sentence) 
    counter = 0 
    while counter < length_of_list: 

     for x in split_sentence: 
      try: 
       if int(x) in xrange(999999999): 
        tuple = ("numbers", x) 
        list1.append(tuple) 
        split_sentence.remove(x) 
        counter += 1 
       else: 
        # print "yes" 
        counter += 1 
      except: 
       # print "no numbers" 
       # print x 
       counter += 1 

    for i in split_sentence: 
     for j in list_of_lists: 
      if i in j: 
       for k, v in list(globals().iteritems()): 
        if j is v: 
         tuple = (k, i) 
         list1.append(tuple) 
         # print list1 
        else: 
         pass 
      else: 
       pass 
    print list1 



scan = scan("door bear north south go stop the in 23 9000000") 
scan 
0

以下的代碼對於所有測試情況下工作,除了test_errors()測試用例(最後測試用例lexicon_tests)。有下面的代碼置於lexicon.py。註釋lexicon_tests.py中的test_errors()函數並運行nosetests。

lexicon.py

from itertools import izip 
direction = {'north':('direction','north'), 'south':('direction','south'),'east':('direction','east'), 'west':('direction','west')} 
verbs  = {'go':('verb', 'go'), 'stop':('verb', 'stop'), 'kill':('verb', 'kill'), 'eat':('verb', 'eat')} 
stop  = {'the':('stop','the'), 'in':('stop','in'), 'of':('stop','of'), 'from':('stop','from'), 'at':('stop','at'), 'it':('stop','it')} 
nouns  = {'door':('noun','door'),'bear':('noun','bear'),'princess':('noun','princess'),'cabinet':('noun','cabinet')} 
numbers = {'1234':('number', 1234),'3':('number', 3),'91234':('number', 91234)} 


class lexicon(object): 

    def scan(self, sentence): 
     self.flag='' 
     self.list_var=[] 
     self.sentence = sentence 
     self.words =self.sentence.split() 
     for k1,k2,k3 in izip(direction,verbs,nouns): 
      self.j=0 
      while self.j < len(self.words): 
        if direction[k1][1] == self.words[self.j] : 
         self.flag='d' 
         break 
        elif verbs[k2][1] == self.words[self.j] : 
         self.flag='v' 
         break 
        elif nouns[k3][1] == self.words[self.j] : 
         self.flag='n' 
         break 
        self.j=self.j+1 
     for k4 in numbers: 
      self.j=0 
      while self.j < len(self.words): 
        if str(numbers[k4][1]) == self.words[self.j] : 
         self.flag='nu' 
         break 
        self.j=self.j+1 
     for k5 in stop: 
      self.j=0 
      while self.j < len(self.words): 
       if stop[k5][1] == self.words[self.j] : 
         print 'in if set flag' 
         self.flag='s' 
         break 
       self.j=self.j+1 

     if self.flag =='d': 
      if len(self.words) == 1: 
       self.list_var.append(direction.get(self.words[0])) 
       return self.list_var 
      else : 
       self.i = 0 
       while self.i < len(self.words): 
        self.list_var.append(direction.get(self.words[self.i])) 
        self.i=self.i+1; 
       return self.list_var 
     elif self.flag == 'v': 
      if len(self.words) == 1: 
       self.list_var.append(verbs.get(self.words[0])) 
       return self.list_var 
      else : 
       print "else" 
       self.i = 0 
       while self.i < len(self.words): 
         self.list_var.append(verbs.get(self.words[self.i])) 
         self.i=self.i+1; 
       return self.list_var 
     elif self.flag == 'n': 
      if len(self.words) == 1: 
       self.list_var.append(nouns.get(self.words[0])) 
       return self.list_var 
      else : 
       self.i = 0 
       while self.i < len(self.words): 
         self.list_var.append(nouns.get(self.words[self.i])) 
         self.i=self.i+1; 
       return self.list_var 
     elif self.flag == 'nu': 
      if len(self.words) == 1: 
       self.list_var.append(numbers.get(self.words[0])) 
       return self.list_var 
      else : 
       self.i = 0 
       while self.i < len(self.words): 
         self.list_var.append(numbers.get(self.words[self.i])) 
         self.i=self.i+1; 
       return self.list_var 
     elif self.flag == 's': 
      if len(self.words) == 1: 
        self.list_var.append(stop.get(self.words[0])) 
        return self.list_var 
      else : 
       self.i = 0 
       while self.i < len(self.words): 
        self.list_var.append(stop.get(self.words[self.i])) 
        self.i=self.i+1; 
       return self.list_var 

lexicon_tests.py

from nose.tools import * 
from ex48.lexicon import lexicon 

lex=lexicon() 
def test_directions(): 
    print lex.scan("north") 
    assert_equal(lex.scan("north"), [('direction', 'north')]) 
    result = lex.scan("north south east") 
    assert_equal(result, [('direction', 'north'), 
          ('direction', 'south'), 
          ('direction', 'east')]) 

def test_verbs(): 
    assert_equal(lex.scan("go"), [('verb', 'go')]) 
    result = lex.scan("go kill eat") 
    assert_equal(result, [('verb', 'go'), 
          ('verb', 'kill'), 
          ('verb', 'eat')]) 

def test_nouns(): 
    assert_equal(lex.scan("bear"), [('noun', 'bear')]) 
    result = lex.scan("bear princess") 
    assert_equal(result, [('noun', 'bear'), 
          ('noun', 'princess')]) 
def test_numbers(): 
    assert_equal(lex.scan("1234"), [('number', 1234)]) 
    result = lex.scan("3 91234") 
    assert_equal(result, [('number', 3), 
          ('number', 91234)]) 
def test_stops(): 
    assert_equal(lex.scan("the"), [('stop', 'the')]) 
    result = lex.scan("the in of") 
    assert_equal(result, [('stop', 'the'), 
          ('stop', 'in'), 
          ('stop', 'of')]) 

'''def test_errors(): 
    assert_equal(lexicon.scan("ASDFADFASDF"), [('error', 'ASDFADFASDF')]) 
    result = lexicon.scan("bear IAS princess") 
    assert_equal(result, [('noun', 'bear'), 
          ('error', 'IAS'), 
          ('noun', 'princess')])''' 

類似的實現可以爲test_errors()函數來完成。

0

我的完整代碼。

lexicon.py

directions = ("north", "south", "east", "west", "down", "up", "left", "right", "back") 
verbs = ("go", "stop", "kill", "eat") 
stops = ("the", "in", "of", "from", "at", "it") 
nouns = ("door", "bear", "princess", "cabinet") 

def select(raw_word): 
    word = raw_word.lower() 
    if word in directions: 
     return ("direction", raw_word) 
    elif word in verbs: 
     return ("verb", raw_word) 
    elif word in stops: 
     return ("stop", raw_word) 
    elif word in nouns: 
     return ("noun", raw_word) 
    else: 
     try: 
      return ("number", int(raw_word)) 
     except ValueError: 
      return ("error", raw_word) 

def scan(words): 
    word_list = str(words).split() 
    return map(select, word_list) 

總共24行。