← 都来码 / Dolaima← 例程索引perl/app/wordcount.pl原文

perl/app/wordcount.pl · 675 字节 · 下载原文

# Perl 前端示例 3 —— 词频统计(Perl 的看家本领:数组 + 哈希 + 字符串)
# Perl frontend example 3 — word frequency counting
#
#   vml run examples/perl/app/wordcount.pl

my $text = "the quick brown fox jumps over the lazy dog the fox";

# split 切词,哈希计频
my @words = split(" ", $text);
my %count;
foreach my $w (@words) {
    $count{$w} = $count{$w} + 1;
}

print "total words: ", scalar(@words), "\n";
print "distinct words: ", scalar(keys %count), "\n";

# 逐个打印出现过的词(按插入顺序 —— 本子集没有 sort,见 README)
foreach my $k (keys %count) {
    print sprintf("  %-6s %d", $k, $count{$k}), "\n";
}