学习Python艰苦的方法练习48的帮助

时间:2011-07-30 05:01:58

标签: python python-2.7

我正在通过Learn Python The Hard Way开展工作,并在练习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 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分: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

答案 2 :(得分:0)

这是在艰难的学习Python中练习48的完整解决方案

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

答案 3 :(得分:0)

我也在努力完成这项工作,我花了几天才把它弄好(至少我认为是对的)。 在编程方面,我是一个完整的菜鸟,我想分享我的解决方案,以获得你们的反馈,看它是否能很好地完成工作。 在此先感谢您的帮助!

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

答案 4 :(得分: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()函数进行类似的实现。

答案 5 :(得分: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行。