3

私は、誰かがファイルから情報を読み取り、最も一般的に使用されている単語を整理し、各単語が使用された回数を返すことに成功したという投稿を見つけました。入力はコマンドライン引数からのものでしたが、同じスクリプトを実行してから、ファイル名を入力としてスクリプトで実行したいと考えています。私が間違っていることを見つけることができません。

print "Type the name of the file: ";
chomp(my $file = <>);

open (FILE, "$file") or die;

while (<FILE>){
    $seen{$_}++ for split /\W+/;
}

my $count = 0;
for (sort {
    $seen{$b} <=> $seen{$a}
              ||
       lc($a) cmp lc($b)
              ||
          $a  cmp  $b
} keys %seen)
{
    next unless /\w/;
    printf "%-20s %5d\n", $seen{$_}, $_;
    last if ++$count > 100;
}
close (FILE);

現時点での私の結果は次のとおりです。

15                       0
15                       0
10                       0
10                       0
10                       0
5                        1
5                        0
5                        0
5                        0
5                        0

私が望む結果は次のとおりです。

<word>             <number of occurances>
<word>             <number of occurances>
<word>             <number of occurances>
<word>             <number of occurances>
<word>             <number of occurances>
<word>             <number of occurances>
4

3 に答える 3

2

この線

printf "%-20s %5d\n", $seen{$_}, $_;

あなたが意図したものの逆です。$_は文字列で、$seen{$_}はテキストに出現する回数$_(数値) であるため、次のいずれかを言いたい

printf "%-20s %5d\n", $_, $seen{$_};

また

printf "%5d %-20s\n", $seen{$_}, $_;
于 2012-10-10T17:55:06.927 に答える
0

2つのこと:

  1. $seenの代わりに、ユーザーが入力したファイル入力を変数に読み込んでいます$file

  2. 末尾の newlin を取り除くには、受け取った入力をむさぼり食う必要があります。

    my $file= <>;
    chomp($file);
    

    または短い形式:

    chomp(my $file = <>);
    
于 2012-10-10T16:22:37.570 に答える
0

2 行目では、開くファイルの名前を $seen ではなく $file に入れます。そう:

chomp(my $file = <>);

chomp は最後に (Enter キーを押して) 改行を取り除きます。

于 2012-10-10T16:24:34.423 に答える