Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rid of warning "DeprecationWarning generator 'ngrams' raised StopIteration"

While working on a Kaggle notebook I ran into an issue. The following code block:

from nltk import ngrams
def grams(tokens):
    return list(ngrams(tokens, 3))
negative_grams = preprocessed_negative_tweets.apply(grams)

resulted in a red box appearing saying

/opt/conda/bin/ipython:5: DeprecationWarning: generator 'ngrams' raised StopIteration

The variable preprocessed_negative_tweets is a Pandas data frame containing tokens.

Anyone know how to make this go away?

(Full notebook available here)

like image 672
langkilde Avatar asked Apr 25 '17 17:04

langkilde


People also ask

How do I fix DeprecationWarning in Python?

How do I remove deprecation warning in Python? Use warnings. filterwarnings() to ignore deprecation warnings Call warnings. filterwarnings(action, category=DeprecationWarning) with action as "ignore" and category set to DeprecationWarning to ignore any deprecation warnings that may rise.

What is a DeprecationWarning in Python?

DeprecationWarning. Base category for warnings about deprecated features when those warnings are intended for other Python developers (ignored by default, unless triggered by code in __main__ ). SyntaxWarning. Base category for warnings about dubious syntactic features.


2 Answers

To anyone else who doesn't want or can't suppress the warning.

This is happening because ngrams is raising StopIteration exception to end a generator, and this is deprecated from Python 3.5.

You could get rid of the warning by changing the code where the generator stops, so instead of raising StopIteration you just use Python's keyword return.

More on: PEP 479

like image 88
carla08 Avatar answered Nov 08 '22 18:11

carla08


You can use a wrapper like this one:

def get_data(gen):
    try:
        for elem in gen:
            yield elem
    except (RuntimeError, StopIteration):
        return

and then (according to your example):

data = get_data(ngrams(tokens, 3))

should do the trick

like image 31
Most Wanted Avatar answered Nov 08 '22 19:11

Most Wanted