如果引发异常,是否可以继续执行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形式执行此操作的方法吗?
答案 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
我认为理解起来要容易得多,并且AttributeError
和parser
来电不会抓住stem