【问题标题】:Perl Program to Count Two Character Frequencies计算两个字符频率的 Perl 程序
【发布时间】:2018-04-24 11:42:40
【问题描述】:

我正在尝试在文本文件中查找两个字符串并将它们及其频率打印出来。

#!/usr/bin/perl
#digram finder
use strict; use warnings;
#finds digrams in a file and prints them and their frequencies out

die "Must input file\n" if (@ARGV != 1);

my ($file) = @ARGV;

my %wordcount;


open (my $in, "<$file") or die "Can't open $file\n";

while (my $words = <$in>){
        chomp $words;
        my $length = length($words);
        for (my $i = 0; $i<$length; $i++){
                my $duo = substr($words, $i; 2);
                if (not exists $wordcount{$duo}){
                        $wordcount{$duo} = 1;
                }
                else {
                        $wordcount{$duo}++;
                }
        }
}

foreach my $word (sort {$wordcount{$b} cmp $wordcount{$a}} keys %wordcount){
                print "$word\t$wordcount{$duo}\n";
}


close($in);
  1. 首先我将文本文件设置为字符串 $words。
  2. 然后,我运行一个 for 循环并在 $words 的每个位置创建一个子字符串 $duo
  3. 如果哈希 %wordcount 中不存在 $duo,则程序会创建密钥 $duo
  4. 如果 $duo 确实存在,则该键的计数增加 1
  5. 然后程序按频率递减的顺序打印出图表及其频率

当我尝试运行代码时,我收到错误消息,我忘记在第 17 行声明 $word,但我什至没有字符串 $word。我不确定此错误消息来自何处。有人可以帮我找出错误的来源吗?

谢谢

【问题讨论】:

  • 如果这是字面意思你的代码,那么有一个错字:substr($words, $i; 2);——它应该有一个,而不是;。所以substr($words, $i, 2);。但这应该会给你一个syntax error 之类的。
  • 会不会是你实际上有$word 而不是$words,只是一个错字?

标签: arrays perl sorting hash


【解决方案1】:

我最好的猜测是你实际上有$word 而不是$words;一个错字。如果编译在文本中找到符号$word,那么它可能就在那里。

不过,我还想对代码发表评论。清理后的版本

while (my $words = <$in>) {
    chomp $words;
    my $last_duo_idx = length($words) - 2;
    for my $i (0 .. $last_duo_idx) {
        my $duo = substr($words, $i, 2); 
        ++$wordcount{$duo};
    }   
}

my @skeys = sort { $wordcount{$b} <=> $wordcount{$a} } keys %wordcount;

foreach my $word (@skeys) {
    print "$word\t$wordcount{$word}\n";
} 

这可以在虚构的文件上正确运行。 (我单独排序只是为了不跑出页面。)

评论

  • 需要在该行的最后一个前停止,substr0开始;因此-2

  • 几乎不需要 C 风格的循环

  • 这里不需要测试密钥是否存在。如果它不存在,则 autovivified(已创建),然后使用 ++ 递增到 1;否则计数会增加。

  • 要按数字排序,请使用&lt;=&gt;,而不是cmp

  • 错别字:

    • substr($words, $i; 2) 需要 , 而不是 ;,所以 substr($words, $i, 2)
    • 打印中的$wordcount{$duo} 应为$wordcount{$word}
  • 我不确定命名:为什么一行文本称为$words

【讨论】:

    猜你喜欢
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 2020-03-20
    • 1970-01-01
    • 2012-06-04
    相关资源
    最近更新 更多