python - 多次捕获相同的异常

标签 python python-3.x

<分区>

如果引发异常,是否有任何方法可以继续执行 try block ?我认为答案是否定的,但我认为下面的代码很难看。

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 形式做到这一点吗?

最佳答案

我会这样改写:

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

我认为它更容易理解并且不会在 parserstem 调用中捕获 AttributeError

关于python - 多次捕获相同的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42376965/

相关文章:

python - 为什么这个脚本在输出中打印一个无关的 'none'

python - 如何使用 Pandas 在时间序列中插入经纬度点

python - For循环调用urllib.urlopen().getcode()很慢

python - 如何添加每列均值的额外卷?

python - 为什么我的reverse()方法在python 3中不起作用?

python - PyQt5 GUI 退出时为 "Python has stopped working"

python - 使用 multiprocessing.manager 的问题

python - Docker gremlin-服务器 : "Cannot assign requested address"

python - 在 Python 3 中导入 numba 时出错

python - 如何防止按键在 QPlainTextEdit 中起作用