Azaghal has asked for the wisdom of the Perl Monks concerning the following question:
Hi,
I've got a list of words (~60k words) and a big text file (~40M lines).
I would like to find the number of occurrences of each word from the list in the text file.
So far I've tried to put the list in a hash, go through each line of the text and increment the associated value each time I see it in the text (with an really basic regex).
Problem is, my code seems to be running fine on a small sample, but is taking ages with the real files. How can I improve my code ?
use strict; use warnings; use utf8::all; my $listfile = "list.txt"; open IN, '<', $listfile or die "could not open $listfile"; binmode(IN, ":utf8"); open OUT, '>', "result.txt" or die "could not open out"; binmode(OUT, ":utf8"); my %count; my @lists = (); while (my $line1 = <IN>) { chomp (my $key1 = (split /\t/, $line1)[0]); push(@lists,$key1); } close IN; foreach my $list (@lists) { $count{$list} = 0; } my $textfile = "textfile.txt"; open my $fh, '<', $textfile or die "Could not open '$textfile' $!"; while (my $line = <$fh>) { chomp $line; foreach my $mot (keys (%count)) { chomp $mot; foreach my $str ($line =~ /$mot/g) { $count{$str}++; } } } foreach my $word (reverse sort { $count{$a} <=> $count{$b} } keys %cou +nt) { print OUT "$word\t$count{$word}\n"; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Count number of occurrences of a list of words in a file
by Athanasius (Archbishop) on May 09, 2018 at 16:11 UTC | |
by Tux (Canon) on May 09, 2018 at 16:31 UTC | |
|
Re: Count number of occurrences of a list of words in a file (updated)
by AnomalousMonk (Archbishop) on May 09, 2018 at 16:32 UTC | |
by Azaghal (Novice) on May 11, 2018 at 15:33 UTC | |
by AnomalousMonk (Archbishop) on May 11, 2018 at 19:44 UTC | |
|
Re: Count number of occurrences of a list of words in a file
by Veltro (Hermit) on May 09, 2018 at 22:15 UTC | |
by Cristoforo (Curate) on May 09, 2018 at 22:28 UTC | |
by AnomalousMonk (Archbishop) on May 09, 2018 at 22:27 UTC |