用Perl语言:写一个程序,读入一串单词(一个单词一行),输出每一个单词出现的次数。 求算法。
(提示:如果某个作为数字使用值是undefined的,会自动将它转换为0。)如果输入单词为fred,barney,dino,wilma,fred(在不同行中),则输出的f...
(提示:如果某个作为数字使用值是undefined 的,会自动将它转换为0。)如果输入单词为fred, barney, dino, wilma, fred(在不同行中),则输出的fred 将为2。作为额外的练习,可以将输出的单词按照ASCII 排序。
#!/usr/bin/perl
use strict;
use warnings;
print "Hello, World...\n";
#ex7-2
#未完成程序,无法通过输入创建哈希表
#无法打印出word_count
open (IN, 'D:\\words.txt ') || die $!;
my @words = (<IN>);
close IN;
my $line = "";
my %word = ();
my @word_list = ();
my @word_count = ();
my $i = 0;
foreach $line(@words){
chomp($line);
print $line ."\n";
$word_list[$i++] = $line;
}
my $j = 0;
my $count = @word_list;
my $count_list = 0;
for ($i = 0; $i < $count;$i++) {
$count_list = 1;
$line = $word_list[$i];
print "$line : $count_list\n";
$word_count[0] = 1;
for ($j = $i + 1; $j < $count;$j++) {
if ($word_list[$j] eq $line) {
$count_list++;
$line = $word_list[$j];
print "$line : $count_list\n";
$word_count[$j - 1] = $count_list;
continue;
} else {
$word_count[$j] = 1;
print "$word_list[$j] : $word_count[$j]\n";
}
}
}
print "@word_count\n";
$count_list = @word_count;
for ($i = 0; $i < $count_list;$i++) {
print "$word_count[$i]\n";
} 展开
#!/usr/bin/perl
use strict;
use warnings;
print "Hello, World...\n";
#ex7-2
#未完成程序,无法通过输入创建哈希表
#无法打印出word_count
open (IN, 'D:\\words.txt ') || die $!;
my @words = (<IN>);
close IN;
my $line = "";
my %word = ();
my @word_list = ();
my @word_count = ();
my $i = 0;
foreach $line(@words){
chomp($line);
print $line ."\n";
$word_list[$i++] = $line;
}
my $j = 0;
my $count = @word_list;
my $count_list = 0;
for ($i = 0; $i < $count;$i++) {
$count_list = 1;
$line = $word_list[$i];
print "$line : $count_list\n";
$word_count[0] = 1;
for ($j = $i + 1; $j < $count;$j++) {
if ($word_list[$j] eq $line) {
$count_list++;
$line = $word_list[$j];
print "$line : $count_list\n";
$word_count[$j - 1] = $count_list;
continue;
} else {
$word_count[$j] = 1;
print "$word_list[$j] : $word_count[$j]\n";
}
}
}
print "@word_count\n";
$count_list = @word_count;
for ($i = 0; $i < $count_list;$i++) {
print "$word_count[$i]\n";
} 展开
1个回答
展开全部
如果你看得懂的话:
#!/usr/bin/perl
use strict;
use warnings;
my %count;
while(<>){
chomp;
$count{$_}++;
}
print "$_: $count{$_}\n" for sort keys %count;
#!/usr/bin/perl
use strict;
use warnings;
my %count;
while(<>){
chomp;
$count{$_}++;
}
print "$_: $count{$_}\n" for sort keys %count;
更多追问追答
追问
非常感谢。
但是程序运行的时候不正确。
追答
[~/tmp/test]$ perl wc
a
b
cd
dc
a
b
a: 2
b: 2
cd: 1
dc: 1
[ ~/tmp/test]$ cat wc
#!/usr/bin/perl
use strict;
use warnings;
my %count;
while(){
chomp;
$count{$_}++;
}
print "$_: $count{$_}\n" for sort keys %count;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询