Yet another solution to word counting problem in Perl!
Today I found a post about word counting problem. While I hadn’t been impressed in suggested solutions, and I’ve known before that awk & sed solution would be the smallest and the simplest one, I decided to write my own solution to this problem in Perl!.
I stand on opinion that Perl! in some cases could be useful, because it has some good piping
flags like file processing flag, inline editing. Perl! also has some good special variables like @, $, $1, $2 and etcetera.
Unfortunately, my solution doesn’t look pretty enough and I think it can be improved somehow, but I think it can show some powerful sides o programming on Perl!.
If you hadn’t read the whole text above, here is the task :
Read a file of text, determine the n most frequently used words, and print out a sorted list of those words along with their frequencies.
And my solution
#!/usr/bin/perl
# WE DON"T WANT TO BE STRICT (SORRY)
binmode( STDOUT, 'utf8:' );
open(FILE, , "<:encoding(utf8)", "lt1.txt") or die;
#binmode( FILE, 'utf8:' );
while (<FILE>) {
$seen{lc($_)}++ for split /[[:punct:]\s]+/gm ;
}
delete $seen{''};
printf ("%8s - %5s\n", $_, $seen{$_})
for (sort { $seen{$b} <=> $seen{$a} } keys %seen)[0..100];
Possible result for the first volume of ‘War and Peace’ book by Leo Tolstoy :
PS. Thanks, I know about ‘strict’ mode and warnings.
bash-3.2$ ./most.pl
и - 21422
в - 11134
не - 8780
что - 8367
он - 7493
на - 6795
с - 5953
как - 4137
его - 3957
то - 3728
к - 3470
я - 3108
но - 2782
она - 2752
это - 2586
было - 2519
а - 2140
так - 2032
сказал - 2016
по - 1972
за - 1951
о - 1909
из - 1887
все - 1852
же - 1821
от - 1773
ему - 1765
ее - 1700
только - 1621
был - 1584
бы - 1508
пьер - 1401
князь - 1354
для - 1325
у - 1296
еще - 1158
когда - 1145
вы - 1098
чтобы - 998
вс - 981
они - 951
да - 927
того - 924
сноска - 923
теперь - 916
него - 914
была - 913
были - 906
ни - 889
ты - 841
наташа - 822
себя - 819
этого - 804
мне - 803
андрей - 801
их - 791
или - 790
том - 780
быть - 773
уже - 752
время - 731
сказала - 715
которые - 682
до - 682
себе - 675
ей - 664
говорил - 658
который - 641
во - 639
нет - 637
чем - 637
de - 624
вот - 623
опять - 619
меня - 616
этот - 613
тем - 610
мы - 597
всех - 578
под - 578
ничего - 574
княжна - 570
ну - 568
потому - 561
очень - 549
после - 546
есть - 543
своей - 543
ростов - 535
ли - 528
марья - 514
при - 507
лицо - 502
человек - 501
вдруг - 500
один - 492
ним - 491
будет - 484
ежели - 479
будто - 479
пьера - 475