如何统计单词对并输出文件


my $line = "The quick brown fox jumps over the lazy dog.";
while ($line =~ /(w+)s(?=(w+b))/g) {
print("$1 $2n");
}

**目前将输出快速敏捷的棕色棕色狐狸…

是否有一种方法可以输出包含单词计数的文本文件,例如:快速:3(发生次数)敏捷的棕色:2棕色狐狸:5…

也许我们可以用

$wordcount{$word} += 1;

当然,任何可行的解决方案都是受欢迎的,非常感谢大家。附注:由于我是一个超级初学者,所以我为模糊的表达道歉。

* *

可以使用一个散列,将单词对(键)映射到出现的次数(值)。

的例子:

#!/bin/perl
use strict;
use warnings;
my $line = "The quick brown fox jumps over the lazy dog.";
my %paircount;
while ($line =~ /(w+)s+(?=(w+b))/g) {
# put the word pair in the map and increase the count
$paircount{"$1 $2"}++;
}
# print the result
while(my($key, $value) = each %paircount) {
print "$key : $value time(s)n";
}

可能的输出:

fox jumps : 1 time(s)
lazy dog : 1 time(s)
over the : 1 time(s)
the lazy : 1 time(s)
brown fox : 1 time(s)
jumps over : 1 time(s)
quick brown : 1 time(s)
The quick : 1 time(s)

最新更新