import click
from textkit.utils import read_tokens, write_csv


@click.command('count')
@click.argument('tokens', type=click.File('r'), default=click.open_file('-'))
@click.option('--sep', default=',',
              help='Separator between token and count in output.',
              show_default=True)
def count_tokens(sep, tokens):
    '''Count unique tokens in a list of tokens.
    Tokens are sorted by top counts.'''
    content = read_tokens(tokens)
    counts = sort_counts(get_counts(content))

    # using csv writer to ensure proper encoding of the seperator.
    rows = [map(str, vals) for vals in counts]
    write_csv(rows, sep)


def get_counts(tokens):
    '''Count unique tokens in a list'''
    counts = {}
    for token in tokens:
        if token in counts:
            counts[token] += 1
        else:
            counts[token] = 1
    return counts


def sort_counts(counts):
    '''Sorts dict of counts by count and returns array of counts'''
    return sorted(counts.items(), key=lambda count: count[1], reverse=True)

@@ -295,16 +295,134 @@
 t=True)%0A
+@click.option('--limit', default=-1, type=click.INT,%0A              help='Only output the top N most frequent tokens')%0A
 def coun
@@ -434,16 +434,23 @@
 ens(sep,
+ limit,
  tokens)
@@ -620,16 +620,225 @@
 tent))%0A%0A
+    # we want the argument type to be an INT - but python only%0A    # has support for a float infinity. So if it the limit is negative,%0A    # it becomes infinite%0A    if limit %3C 0:%0A        limit = float('inf')%0A%0A
     # us
@@ -926,16 +926,21 @@
 als) for
+ ind,
  vals in
@@ -940,22 +940,48 @@
 vals in 
-counts
+enumerate(counts) if ind %3C limit
 %5D%0A    wr

Add `--limit` flag to provide a limit to the number of results output (we could also suggest relying on just `head` but I understand the benefit of having this built in.