多次捕获相同的异常

时间:2017-02-21 20:07:12

标签: python python-3.x

如果引发异常,是否可以继续执行try阻止?我认为aswer不是,但我认为以下代码很难看。

def preprocess(self, text):
    try:
        text = self.parser(text)
    except AttributeError:
        pass
    try:
        terms = [term for term in text if term not in self.stopwords]
        text = list_to_string(terms)
    except AttributeError:
        pass
    try:
        terms = [self.stemmer.stem(term) for term in text]
        text = list_to_string(terms)
    except AttributeError:
        pass
    return text

还有另一种以pythonic形式执行此操作的方法吗?

1 个答案:

答案 0 :(得分:2)

我会用这种方式重写它:

def preprocess(self, text):
    if hasattr(self, 'parser'): 
        text = self.parser(text)

    if hasattr(self, 'stopwords'): 
        terms = [term for term in text if term not in self.stopwords]
        text = list_to_string(terms)

    if hasattr(self, 'stemmer'):        
        terms = [self.stemmer.stem(term) for term in text]
        text = list_to_string(terms)

    return text

我认为理解起来要容易得多,并且AttributeErrorparser来电不会抓住stem