使用Perl计算消息中的字符频率
我正在写一个Perl脚本来查找消息中字符出现的频率.这是我遵循的逻辑:
>使用getc()从消息中一次读取一个char并将其存储到数组中. 问题:我不希望程序重新计算字符的频率(如果已经计算过).例如,如果字符“a”出现3次,则对于第一次运行,它会计算正确的频率.但是,在下一次出现“a”时,由于循环从该索引运行到结束,因此频率为(实际频率-1).类似于第三次出现,频率是(实际频率-2). 要解决这个问题.我使用了另一个临时数组,我将推送其频率已被评估的char. 然后在下一轮for循环中,在进入内部for循环之前,我将当前char与已计算的chars数组进行比较并设置一个标志.基于该标志,内部for循环运行. 这不适合我.结果仍然相同. 这是我为完成上述操作而编写的代码: #!/usr/bin/perl use strict; use warnings; my $input=$ARGV[0]; my ($c,$ch,$flag,$s,@arr,@temp); open(INPUT,"<$input"); while(defined($c = getc(INPUT))) { push(@arr,$c); } close(INPUT); my $length=$#arr+1; for(my $i=0;$i<$length;$i++) { $count=0; $flag=0; $ch=$arr[$i]; foreach $s (@temp) { if($ch eq $s) { $flag = 1; } } if($flag == 0) { for(my $k=$i;$k<$length;$k++) { if($ch eq $arr[$k]) { $count = $count+1; } } push(@temp,$ch); print "The character "".$ch."" appears ".$count." number of times in the message"."n"; } } 解决方法
如果要对整个文件执行单个字符计数,请使用其他方法发布的任何建议方法.如果你想要计算所有出现次数
对于文件中的每个字符,我建议: #!/usr/bin/perl use strict; use warnings; # read in the contents of the file my $contents; open(TMP,"<$ARGV[0]") or die ("Failed to open $ARGV[0]: $!"); { local($/) = undef; $contents = <TMP>; } close(TMP); # split the contents around each character my @bits = split(//,$contents); # build the hash of each character with it's respective count my %counts = map { # use lc($_) to make the search case-insensitive my $foo = $_; # filter out newlines $_ ne "n" ? ($foo => scalar grep {$_ eq $foo} @bits) : () } @bits; # reverse sort (highest first) the hash values and print foreach(reverse sort {$counts{$a} <=> $counts{$b}} keys %counts) { print "$_: $counts{$_}n"; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |