以艰难的方式学习Python Ex 48

时间:2015-02-05 05:02:39

标签: python python-2.7

我正在尝试完成学习Python的艰难之路练习48,当我使用nosetests进行测试时,令我沮丧的是,我在test_numbers()和test_errors()上得到了KeyError。这里列出的是我使用的代码(代码主要基于DairyLee的解决方案):

lexicon = {}
for directions in ['north', 'south', 'east', 'west', 'down', 
                   'up', 'left', 'right', 'back']:
    lexicon.update({directions: 'direction'})
for verbs in ['go', 'stop', 'kill', 'eat']:
    lexicon.update({verbs: 'verb'})
for stops in ['the', 'in', 'of', 'from', 'at', 'it']:
    lexicon.update({stops: 'stop'})
for nouns in ['door', 'bear', 'princess', 'cabinet']:
    lexicon.update({nouns: 'noun'})

stuff = raw_input('> ')
words = stuff.lower().split()

def scan(sentance):
    words = sentance.lower().split()
    pairs = []
    for word in words:
        if lexicon[word] == 'direction':
            pairs.append(('direction', word))
        elif lexicon[word] == 'verb':
            pairs.append(('verb', word))
        elif lexicon[word] == 'noun':
            pairs.append(('noun', word))
        elif lexicon[word] == 'stop':
            pairs.append(('stop', word))
        elif lexicon[word] == 'noun':
            pairs.append(('noun', word))
        elif convert_number(word) != None:
            pairs.append(('number', convert_number(word)))
        else:
            pairs.append(('error', word))
    return pairs

def convert_number(s):
    try:
        return int(s)
    except ValueError:
        return None

这是页面。 http://learnpythonthehardway.org/book/ex48.html包含测试的相关部分:

def test_numbers():
    assert_equal(lexicon.scan("1234"), [('number', 1234)])
    result = lexicon.scan("3 91234")
    assert_equal(result, [('number', 3),
                          ('number', 91234)])


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')])

根据我的理解,似乎只要密钥不在词典词典中就不会继续测试,这很奇怪,因为我在for循环的末尾放了一个else语句。非常感谢帮助!

2 个答案:

答案 0 :(得分:1)

这是我最后的答案。谢谢Asad的快捷方式。

lexicon = {}
for directions in ['north', 'south', 'east', 'west', 'down', 
                   'up', 'left', 'right', 'back']:
    lexicon.update({directions: 'direction'})
for verbs in ['go', 'stop', 'kill', 'eat']:
    lexicon.update({verbs: 'verb'})
for stops in ['the', 'in', 'of', 'from', 'at', 'it']:
    lexicon.update({stops: 'stop'})
for nouns in ['door', 'bear', 'princess', 'cabinet']:
    lexicon.update({nouns: 'noun'})



stuff = raw_input('> ')
words = stuff.lower().split()

def scan(sentence):
    words = sentence.split()
    pairs = []
    for word in words:
        try:
            k = word.lower()
            pairs.append((lexicon[k], word))
        except KeyError:
            if convert_number(word) != None:
                 pairs.append(('number', int(word)))
            else:
                pairs.append(('error', word))
    return pairs

def convert_number(s):
    try:
        return int(s)
    except ValueError:
        return None

答案 1 :(得分:0)

def scan(sentence):
  words = sentence.split()
  v = ["go","kill","eat","stop"]
  dw ["north","south","east","west","down","up","left","right","back"]
  sw = ["the","in","of","from","at","it"]
  n = ["door","bear","princess","cabinet"]
  sent = []
  for i in words:
      if i in v:
          result = ('verb', i)
          sent.append(result)
      elif i in dw:
          result = ('direction', i)
          sent.append(result)
      elif i in sw:
          result = ('stop', i)
          sent.append(result)
      elif i in n:
          result = ('noun', i)
          sent.append(result)
      elif i.isdigit() and len(i)<=9:
          result = ('number', int(i))``
          sent.append(result)
      else:
          result = ('error', i)
          sent.append(result)
  return sent