Is there a way to get multiple ngram orders using NTLK instead of obtaining a iterating over a generator?
<p>I need ngrams. I know <code>nltk.utils.ngrams</code> can be used to obtain ngrams, but in practice, the ngrams function returns a generator object. I can always iterate over it and store the ngrams in a list. But is there another, more direct way to obtaining these ngrams in a list without having to iterate over them?</p>

<p>There's actually a built-in function to get multiple orders of ngrams call <code>everygrams</code> ,see <a href="https://github.com/nltk/nltk/blob/develop/nltk/util.py#L504" rel="nofollow">https://github.com/nltk/nltk/blob/develop/nltk/util.py#L504</a></p>

<pre><code>&gt;&gt;&gt; from nltk import everygrams
&gt;&gt;&gt; sent = 'a b c'.split()
# By default, it will extract every possible order of ngrams.
&gt;&gt;&gt; list(everygrams(sent))
[('a',), ('b',), ('c',), ('a', 'b'), ('b', 'c'), ('a', 'b', 'c')]
# You can set a max order or ngrams.
&gt;&gt;&gt; list(everygrams(sent, max_len=2))
[('a',), ('b',), ('c',), ('a', 'b'), ('b', 'c')]
# Or specify a range.
&gt;&gt;&gt; list(everygrams(sent, min_len=2, max_len=3))
[('a', 'b'), ('b', 'c'), ('a', 'b', 'c')]
</code></pre>

python nlp generator nltk n-gram