
>使用getc()从消息中一次读取一个char并将其存储到数组中.
>运行for循环,从索引0开始到此数组的长度.
>此循环将读取数组的每个char并将其分配给temp变量.
>运行另一个嵌套在上面的for循环,它将从被测字符的索引运行到数组的长度.
>使用此字符与当前数组索引字符之间的字符串比较,如果计数器相等,则计数器会递增.
>完成内部For循环后,我打印char的频率用于调试目的.
问题:我不希望程序重新计算字符的频率(如果已经计算过).例如,如果字符“a”出现3次,则对于第一次运行,它会计算正确的频率.但是,在下一次出现“a”时,由于循环从该索引运行到结束,因此频率为(实际频率-1).类似于第三次出现,频率是(实际频率-2).
要解决这个问题.我使用了另一个临时数组,我将推送其频率已被评估的char.
然后在下一轮for循环中,在进入内部for循环之前,我将当前char与已计算的chars数组进行比较并设置一个标志.基于该标志,内部for循环运行.
这不适合我.结果仍然相同.
这是我为完成上述 *** 作而编写的代码:
#!/usr/bin/perluse 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/perluse strict;use warnings;# read in the contents of the filemy $contents;open(TMP,"<$ARGV[0]") or dIE ("Failed to open $ARGV[0]: $!");{ local($/) = undef; $contents = <TMP>;}close(TMP);# split the contents around each charactermy @bits = split(//,$contents);# build the hash of each character with it's respective countmy %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 printforeach(reverse sort {$counts{$a} <=> $counts{$b}} keys %counts) { print "$_: $counts{$_}\n";} 总结 以上是内存溢出为你收集整理的使用Perl计算消息中的字符频率全部内容,希望文章能够帮你解决使用Perl计算消息中的字符频率所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)