如何摆脱警告"DeprecationWarning generator'ngrams'提出StopIteration"

lan*_*lde 8 python ipython nltk kaggle

在使用Kaggle笔记本时,我遇到了一个问题.以下代码块:

from nltk import ngrams
def grams(tokens):
    return list(ngrams(tokens, 3))
negative_grams = preprocessed_negative_tweets.apply(grams)
Run Code Online (Sandbox Code Playgroud)

结果出现了一个红色的盒子

/opt/conda/bin/ipython:5: DeprecationWarning: generator 'ngrams' raised StopIteration
Run Code Online (Sandbox Code Playgroud)

该变量preprocessed_negative_tweets是包含令牌的Pandas数据帧.

有谁知道如何让它消失?

(这里有完整笔记本)

小智 15

对于任何不想或不能抑制警告的人.

发生这种情况是因为ngrams引发StopIteration异常以结束生成器,并且这是从Python 3.5中弃用的.

您可以通过更改生成器停止的代码来消除警告,因此不要StopIteration只是使用Python的关键字return.

更多信息:PEP 479

  • 我有一个生成器:`while True:yield itertools.chain(...)`.你会怎么转换那个? (3认同)
  • @OrangeDog您可以使用:`yield from itertools.chain(...)`. (3认同)