Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Counting and Filtering Words From File

by jwkrahn (Abbot)
on May 09, 2020 at 22:49 UTC ( [id://11116629]=note: print w/replies, xml ) Need Help??


in reply to Counting and Filtering Words From File

I don't understand your "list of excluded characters". In the bash version you are using tr which only works on characters but in the Perl version your list uses two character strings instead of single characters. Also, Perl has a tr/// operator which operates pretty much the same as the command line tool (on single characters).

Your "list of excluded words" would probably be better as a hash.

Reading a file a line at a time shouldn't be a problem as Perl IO is buffered, however, you can change how much data is read in by changing the Input Record Separator ($/) to read in a whole file.

The comment in your program says "# remove non-letter characters", however you are only removing certain punctuation characters.

Perhaps you want something like this:

#!/usr/bin/perl # word counting program use strict; use warnings; use autodie; # list of excluded words my %excluded = map { $_ => 1 } qw( a about although also an and anothe +r are as at be been before between but by can do during for from has how however in in +to is it many may more most etc ); ## list of excluded characters #my @excluded_chars = ( "\\'", "\\:", "\\@", "\\-", "\\~", "\\,", "\\. +", "\\(", # "\\)", "\\?", "\\*", "\\%", "\\/", "\\[", "\\]", "\\=", '"' # ); # Read in whole file (uncomment next line) # local $/; my %count; # this will contain many words while (<>) { # remove punctuation tr{':@\-~,.()*%/[]="}{}d; foreach ( split ) { # remove excluded words next if exists $excluded{ lc() }; ++$count{ lc() }; # count each separate word } } foreach my $word (sort { $count{ $a } <=> $count{ $b } || $a cmp $b } +keys %count) { print "$count{$word} $word\n"; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11116629]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (4)
As of 2024-04-25 23:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found