如何在Python中抛出异常?

时间:2017-11-03 19:55:59

标签: python exception error-handling

我正在尝试使用Python的'langdetect'库在数据框中检测外语。

for e in food['product_name'].dropna():
    if detect(e) == 'zh':
        print e

这里我试图打印在特定列中找到的每个中文单词。

但是,在某些时候我收到此错误消息:

LangDetectException: No features in text.

我理解当找到一个数字,空格或不是单词的字符串(参考代码,邮件地址......)时会发生这种情况。

我想要的只是抛出一个异常并相应地处理这种情况但是我不知道该怎么做。这是我的尝试:

for e in food['product_name'].dropna():
    if detect(e) == 'zh':
        try:
            print e
        except LangDetectException:
            pass

有人可以帮我解决这个写得不好的片段吗?显然它有问题,但我不知道究竟是什么!

1 个答案:

答案 0 :(得分:2)

正如上面的评论中所提到的,异常是通过检测引发的,因此您需要将该调用包装在try块中:

for e in food['product_name'].dropna():
    try:
        if detect(e) == 'zh':
            print e
    except LangDetectException:
        pass
相关问题