News for hackers. Stuff that matters.
Re:The Yoda of Silicon Valley by btilly on Monday December 17, 2018 @06:29PM (#18703261)
It is easy to do in your favorite scripting language. But is unlikely to be as short. Comprehensibility is in the eye of the beholder.

Here is a Perl solution for comparison.

    use strict;
    use warnings;

    my $limit = shift @ARGV;

    my %count;
    for my $line (<>) {
        while ($line =~ /(\w+)/g) {
            $count{lc $1}++;
        }
    }

    @words = sort {$count{$b} <=> $count{$a} or $a cmp $b} keys %count;
    $limit = @words if @words < $limit;
    print "$_\t$count{$_}\n" for @words[0..($limit-1)];
Re:The Yoda of Silicon Valley by lizmat on Sunday December 23, 2018 @06:12PM (#18749039)
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.
Re:The Yoda of Silicon Valley by b2gills on Tuesday December 25, 2018 @01:53AM (#18756324)
I would have written the sort differently

    %bag.sort({ -.value, .key })
Re:The Yoda of Silicon Valley by mkl on Tuesday December 18, 2018 @07:50AM (#18706087)
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).
Re:The Yoda of Silicon Valley by mkesper on Tuesday December 18, 2018 @11:27AM (#18707817)
You don't want to read all input into memory first.
Re:The Yoda of Silicon Valley by mkl on Tuesday December 18, 2018 @03:02PM (#18710013)
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}')