Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Count number of occurrences of a list of words in a file

by Athanasius (Archbishop)
on May 09, 2018 at 16:11 UTC ( [id://1214285]=note: print w/replies, xml ) Need Help??


in reply to Count number of occurrences of a list of words in a file

Hello Azaghal,

The bottleneck occurs here, in the inner loop:

while (my $line = <$fh>) { chomp $line; foreach my $mot (keys (%count)) { chomp $mot; foreach my $str ($line =~ /$mot/g) { $count{$str}++; } } }

If %count contains 60,000 entries, then the foreach loop performs 60,000 regex tests against each line of the input text file! Fortunately, this is quite unnecessary. I would split each line into words and simply lookup these words in the hash; like this (untested):

while (my $line = <$fh>) { chomp $line; my @words = split /\W+/, $line; for my $word (@words) { ++$count{$word} if exists $count{$word}; } }

(You may need to tweak the split regex, depending on the contents of the words in the list file.)

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: Count number of occurrences of a list of words in a file
by Tux (Canon) on May 09, 2018 at 16:31 UTC

    How about this then?

    #!/usr/bin/perl use 5.18.3; use warnings; chomp (my @words = <DATA>); my %cnt = map { $_ => 0 } @words; foreach my $tf (glob "*.log") { printf STDERR " %-40s\r", $tf; open my $fh, "<", $tf or next; while (<$fh>) { $cnt{$_}++ for grep { exists $cnt{$_} } m/(\w+)/g; } } printf "%-20s : %6d\n", $_, $cnt{$_} for sort { $cnt{$b} <=> $cnt{$a} +} @words; __END__ tux dromedary camel dream milk druid monk wizard azaghal perl

    I was more wondering about case sensitiveness

    I timed that against the original approach. My code (with 8 words): 19 seconds, OP code: 57 seconds. That difference will exponentially grow with the number of words: with 23 words 20 seconds versus 175 seconds. Total text size was 273 Mb.


    Enjoy, Have FUN! H.Merijn

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (2)
As of 2024-04-26 05:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found