in reply to Re^2: Counting occurence of a list of word in a file
in thread Counting occurence of a list of word in a file
use strict; use warnings; my %patts; my %counts; my $file = 'patterns.txt'; my $fh; open $fh, '<', $file or die "can not open file $file: $!"; while (<$fh>) { chomp; my ($word1, $word2) = split /:/; $patts{$word1} = $word2; } close $fh; $file = 'text.txt'; open $fh, '<', $file or die "can not open file $file: $!"; while (<$fh>) { chomp; for my $patt (keys %patts) { $counts{$patt} += count_match($_, $patt); } } close $fh; for my $patt (keys %counts) { print "pattern $patt occurs $counts{$patt} times\n"; } sub count_match { my ($str, $regex) = @_; my @words = split /\s+/, $str; my $count = 0; for (@words) { $count++ if /\b$regex\b/ } return $count; } __END__ pattern [Aa]tom[oi] occurs 1 times pattern [Nn]ucle[oi] occurs 3 times
|
|---|