Wednesday, April 13, 2011

counts the frequency of each word in perl

#This code counts the frequency of each word in the sentence by using a hash.

$sentence = "The cat that saw the black cat is a calico.";
$sentence =~ s/[.,?;:'"(){}\[\]]//g; #Remove punctuation

@words = split (/ /, $sentence);

foreach $word (@words) {
    ++$counts{lc($word)};
}

foreach $word (keys %counts) {
   print "$word, $counts{$word}\n";
}

No comments: