【问题标题】:counting letters for each word in a text with Perl用 Perl 计算文本中每个单词的字母
【发布时间】:2011-09-05 13:28:27
【问题描述】:

我正在尝试使用 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__

希望有人给点建议!

【问题讨论】:

  • 您不妨检查一下这个问题:stackoverflow.com/questions/6170985/… 当您进行像您这样的拆分时,您最终会得到 wordWordword, 都被视为不同的词,这可能不是你想要的。

标签: perl count words letters


【解决方案1】:

如果要存储单词的长度,可以使用 hash of hashes。

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";
}

【讨论】:

    【解决方案2】:

    仅供参考 -

    length length($word)
    

    可能是:

    $word =~ s/(\w)/$1/g
    

    它不像 toolic 那样明确的解决方案,但可以为您提供有关此问题的其他观点 (TIMTOWTDI :))

    小解释:

    \wg 修饰符匹配 $word

    中的每个字母

    $1 防止 s///

    覆盖原始 $word

    s/// 返回 $word

    中的字母数(与 \w 匹配)

    【讨论】:

    • 你的意思是$count = $word =~ s/(\w)//g;会得到字母的数量。 ;)
    • @TLP:检查:my $word = "word"; print $word =~ s/(\w)/$1/g; 输出为:7 如果没有 $1,您将用计数的数量覆盖您的 $word字母。
    • 太快了 - 输出是 4 :)
    • 是的,我知道。 ;) 哦,我明白了,我在评论中忘记了$1,我的错。我的意思是如果你把$count放在前面,你会把s///返回的数字存储在里面。所以:$count = $word =~ s/(\w)/$1/g
    【解决方案3】:

    这将在计数旁边打印长度:

      print "$word: $count_of{$word} ", length($word), "\n";
    

    【讨论】:

    • 哦,感谢您的快速答复!它工作正常。我是这样写的: print $word, "\t", $count_of{$word}, "\t", length($word), "\n";
    猜你喜欢
    • 1970-01-01
    • 2011-09-15
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 2023-02-11
    • 2016-05-18
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多