Catch same exception multiple times
本问题已经有最佳答案,请猛点这里访问。
如果出现异常,是否有任何方法可以继续执行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 |
还有另一种方法可以用Python的形式来做这个吗?
我会这样重写它:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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 |
我认为这更容易理解,也不会在