用Perl对每个单词的字母计数

| 我正在尝试编写一个带有Perl的程序,该程序应该返回文件中所有单词的频率和文件中每个单词的长度(不是所有字符的总和!),以从西班牙语文本生成Zipf曲线(不是如果您不知道Zipf的曲线是什么,那就大了)。现在我的问题是:我可以做第一部分,我得到所有单词的频率,但是我不知道如何获得每个单词的长度! :(我知道命令行 $ word_length = length($ words),但是在尝试更改代码后,我真的不知道该在哪里包括它以及如何计算每个单词的长度。 在知道之前,我的代码就是这样:
#!/usr/bin/perl
use strict;
use warnings;

my %count_of;
while (my $line = <>) { #read from file or STDIN
  foreach my $word (split /\\s+/gi, $line){
     $count_of{$word}++;
  }
}
print \"All words and their counts: \\n\";
for my $word (sort keys %count_of) {
  print \"$word: $count_of{$word}\\n\";
}
__END__
我希望有人有任何建议!     
已邀请:
        如果要存储单词的长度,则可以使用哈希散列。
while (my $line = <>) {
    foreach my $word (split /\\s+/, $line) {
        $count_of{$word}{word_count}++;
        $count_of{$word}{word_length} = length($word);
    }
}

print \"All words and their counts and length: \\n\";
for my $word (sort keys %count_of) {
    print \"$word: $count_of{$word}{word_count} \";
    print \"Length of the word:$count_of{$word}{word_length}\\n\";
}
    
        这将在计数旁边打印长度:
  print \"$word: $count_of{$word} \", length($word), \"\\n\";
    
        仅供参考-另一种可能性
length length($word)
可能:
$word =~ s/(\\w)/$1/g
这不是像toolic一样清晰的解决方案,但是可以给您其他有关此问题的观点(TIMTOWTDI :)) 小解释: \\ w和g修饰符匹配$ word中的每个字母 $ 1防止通过s ///覆盖原始$ word s ///返回$ word中的字母数(与\\ w匹配)     

要回复问题请先登录注册