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"; }
In reply to Count number of occurrences of a list of words in a file by Azaghal
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |