perl中统计单词出现频率的一段代码,大家帮我看看我那里错了?
#!/usr/bin/perlopen(MY,"1.txt");while(<MY>){while(/fred/){$words{$1}++;}}foreach$_(ke...
#!/usr/bin/perl
open(MY,"1.txt");while(<MY>){
while(/fred/){
$words {$1}++;
} }
foreach $_ (keys %words){
print "$_$words{$1}\n;
"}
我的txt文本是
fred
barney
fred
dino
wilma
fred 展开
open(MY,"1.txt");while(<MY>){
while(/fred/){
$words {$1}++;
} }
foreach $_ (keys %words){
print "$_$words{$1}\n;
"}
我的txt文本是
fred
barney
fred
dino
wilma
fred 展开
1个回答
2011-11-09
展开全部
#!/usr/bin/perl
use strict;
use warnings;
my %words =();
open(MY,"1.txt")
or die "File problem: $!";
while (<MY>){
$words {$1}++ if /(\w+)/ ;
}
foreach (keys %words) {
print $_, "=> ", $words{$_}, "\n";
}
use strict;
use warnings;
my %words =();
open(MY,"1.txt")
or die "File problem: $!";
while (<MY>){
$words {$1}++ if /(\w+)/ ;
}
foreach (keys %words) {
print $_, "=> ", $words{$_}, "\n";
}
更多追问追答
追问
能解释下这个代码吗? $words {$1}++ if /(\w+)/ ;
追答
## $words {$1}++ if /(\w+)/ ;
-- 如果一行 (在 $_ 里) 匹配到了一个单词,if ($_=~ m/(\w+)/ ) {...}
匹配到的单词在 $1 里
$words{$1} 就加 1 (起始数为0)
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询