4

我正在编写一个 Perl 脚本来找出消息中字符出现的频率。这是我遵循的逻辑:

  • 使用 getc() 从消息中一次读取一个字符并将其存储到数组中。
  • 运行从索引 0 开始到此数组长度的 for 循环。
  • 此循环将读取数组的每个字符并将其分配给临时变量。
  • 运行另一个嵌套在上面的 for 循环,它将从被测试字符的索引运行到数组的长度。
  • 使用此字符和当前数组索引 char 之间的字符串比较,如果它们相等,则递增计数器。
  • 完成内部 For 循环后,我正在打印 char 的频率以进行调试。

问题:我不希望程序重新计算已经计算过的字符的频率。例如,如果字符“a”出现 3 次,那么对于第一次运行,它会计算正确的频率。但是,在下一次出现“a”时,由于循环从该索引运行到结束,因此频率为(实际频率 -1)。与第三次类似,频率为(实际频率 -2)。

为了解决这个问题。我使用了另一个临时数组,我会将已经评估频率的字符推送到该数组中。

然后在 for 循环的下一次运行中,在进入内部 for 循环之前,我将当前字符与评估字符数组进行比较并设置一个标志。基于该标志,内部 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";
}
}
4

5 回答 5

4

你让你的生活变得比它需要的更艰难。使用哈希:

my %freq;

while(defined($c = getc(INPUT)))
{
  $freq{$c}++;
}

print $_, " ", $freq{$_}, "\n" for sort keys %freq;

$freq{$c}++增加存储在 中的值$freq{$c}。(如果未设置或为零,则变为一。)

打印行相当于:

foreach my $key (sort keys %freq) {
  print $key, " ", $freq{$key}, "\n";
}
于 2011-10-16T13:07:30.730 回答
3

如果您想对整个文件进行单个字符计数,请使用其他人发布的任何建议方法。如果您想计算文件中每个字符的所有出现次数,那么我建议:

#!/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";
}
于 2011-10-16T13:45:31.073 回答
2

我不明白您要解决的问题,因此我提出了一种更简单的方法来计算字符串中的字符:

$string = "fooooooobar";
$char = 'o';
$count = grep {$_ eq $char} split //, $string;
print $count, "\n";

这会在 $string (7) 中打印 $char 出现的次数。希望这有助于编写更紧凑的代码

于 2011-10-16T13:20:01.640 回答
1

更快的解决方案:

@result = $subject =~ m/a/g; #subject is your file

print "Found : ", scalar @result, " a characters in file!\n";

当然,您可以将变量放在“a”的位置,或者甚至更好地执行此行来计算您想要计算出现次数的任何字符。

于 2011-10-16T13:05:25.920 回答
1

作为一个单行:

perl -F"" -anE '$h{$_}++ for @F; END { say "$_ : $h{$_}" for keys %h }' foo.txt
于 2011-10-16T15:26:29.957 回答