Why can't I catch the exception in this code?

Question:

I’m trying to detect foreign languages in a dataframe using ‘langdetect’ library for Python.

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

Here im trying to print every chinese word found in a specific column.

However, at some point I get this error message:

LangDetectException: No features in text.

I understand this happens when a number, a blank space or a string that is not a word (reference code, mail address…) is found.

All I want is to catch an exception and handle the situation accordingly BUT i don’t know how to do it. Here’s my attempt:

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

Can someone please help me fix this poorly written snippet ? Obviously there’s something wrong with it but I don’t know what exactly !

Asked By: solub

||

Answers:

As mentioned in the comments above the exception is being raised by detect, so you need to wrap that call in your try block:

for e in food['product_name'].dropna():
    try:
        if detect(e) == 'zh':
            print e
    except LangDetectException:
        pass
Answered By: Luke Smith
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.