Just for reference: a Perl 6 version:
sub MAIN($limit = Inf) {
my %bag is Bag = words.map(&lc);
say "{.key}\t{.value}" for %bag.sort( {
$^b.value cmp $^a.value || $^a.key cmp $^b.key
} )[^$limit]
}
And for what it's worth, the `words` function is lazy, so it won't read all of the words into memory first.I would have written the sort differently
%bag.sort({ -.value, .key })Python is relatively short, batteries included and all that:
import re
import sys
import collections
words = re.findall('[a-z]+', sys.stdin.read().lower())
c = collections.Counter(words)
for word, count in c.most_common(int(sys.argv[1])):
print(f'{count:>7} {word}')
Three times the character count of the Unix pipe version, but IMHO a lot more readable (and generalisable).You don't want to read all input into memory first.
Fair enough.
import re
import sys
import collections
c = collections.Counter()
for line in sys.stdin:
words = re.findall('[a-z]+', line.lower())
c.update(words)
for word, count in c.most_common(int(sys.argv[1])):
print(f'{count:>7} {word}')
Here is a Perl solution for comparison.