accessing elements of a counter containing ngrams
<p>I am taking a string, tokenizing it, and want to look at the most common bigrams, here is what I have got:</p>

<pre><code>import nltk
import collections
from nltk import ngrams

someString="this is some text. this is some more test. this is even more text."
tokens=nltk.word_tokenize(someString)
tokens=[token.lower() for token in tokens if len()&gt;1]

bigram=ngrams(tokens,2)
aCounter=collections.Counter(bigram)
</code></pre>

<p>If I:</p>

<pre><code>print(aCounter)
</code></pre>

<p>Then it will output the bigrams in sorted order. </p>

<pre><code>for element in aCounter:
     print(element)
</code></pre>

<p>Will print the elements, but not with a count, and not in order of the count. I want to do a for loop, where I print out the X most common bigrams in a text.</p>

<p>I am essentially trying to learn both Python and nltk at the same time, so this could be why I am struggling here (I assume this is a trivial thing).</p>

<p>You're probably looking for something that already exists, namely, the <a href="https://docs.python.org/3/library/collections.html#collections.Counter.most_common" rel="nofollow"><code>most_common</code></a> method on counters. From the docs: </p>

<blockquote>
  <p>Return a list of the <code>n</code> most common elements and their counts from the most common to the least. If <code>n</code> is omitted or <code>None</code>, <code>most_common()</code> returns all elements in the counter. Elements with equal counts are ordered arbitrarily:</p>
</blockquote>

<p>You can call it and supply a value <code>n</code> in order to get the <code>n</code> most common value-count pairs. For example:</p>

<pre><code>from collections import Counter

# initialize with silly value.
c = Counter('aabbbccccdddeeeeefffffffghhhhiiiiiii')

# Print 4 most common values and their respective count.
for val, count in c.most_common(4):
    print("Value {0} -&gt; Count {1}".format(val, count))
</code></pre>

<p>Which prints out:</p>

<pre><code>Value f -&gt; Count 7
Value i -&gt; Count 7
Value e -&gt; Count 5
Value h -&gt; Count 4
</code></pre>

python python-3.x nltk n-gram