代码改进,Python 硬道理 ex48

Code improvement, Python the hard way ex48

我在百思不得其解的情况下完成了练习,做出了符合他测试的代码。

WORD_TYPES = {
   'verb' : ['go', 'kill', 'eat'],
   'direction' : ['north', 'south', 'east', 'west'],
   'noun' : ['bear', 'princess'],
   'stop' : ['the','in','of']
} 

def scan(sentance):
    listy = []
    counter = 0
    for word in sentance.split():
        try:
            count = counter
            for key, value in WORD_TYPES.iteritems():
                for ind in value:
                    if ind == word:
                        counter += 1
                        listy.append((key,ind))
            if count == counter:
                raise KeyError
        except KeyError:
            try:
                value = int(word)
                listy.append(('number',value))
            except ValueError:
                listy.append(('error',word))
    return listy

作者希望我们使用 try 和 exceptions,但我觉得我没有有效地使用它们。在这里使用它们的更好方法是什么?另外,什么时候 try 和 excepts 才是真正理想的?也欢迎任何其他改进代码的技巧。

我假设您指的是 http://learnpythonthehardway.org/book/ex48.html

中的练习

作者说在解释数字时使用 tryexcept 到 "cheat",因为一般来说,常用的方法是使用正则表达式。使用 int() 函数尝试将未知单词转换为 int,您可以将失败解释为一个不错的指示,表明它不是数字 - 因此捕获 ValueError 异常。

您对异常的其他使用是不必要的。

The try-except construct is only used for handling exceptions that modules can throw. It should never be used as an alternative to if-else.

此外,您不需要 运行 遍历列表的每个元素来找到匹配项,只需使用 in 运算符即可。

if ind in value:
    # Do Stuff