使用perl查找字符串中唯一单词的最高频率
我写这个脚本是为了获得并打印段落中出现频率最高的独特单词 有关代码-请参阅附件使用perl查找字符串中唯一单词的最高频率,perl,Perl,我写这个脚本是为了获得并打印段落中出现频率最高的独特单词 有关代码-请参阅附件 my $freq; my $word; my $textdata = <<"END_MSG"; mm mm mm mm kk kk kk kkkk kk To pp pp pp pp pp pp. END_MSG foreach $word ( split ( ' ', lc $textdata) { $freq{$word}++; #print $freq{$word};
my $freq;
my $word;
my $textdata = <<"END_MSG";
mm mm mm mm kk kk kk kkkk kk To pp pp pp pp pp pp.
END_MSG
foreach $word ( split ( ' ', lc $textdata)
{
$freq{$word}++;
#print $freq{$word};
#print "..";
}
use sort 'stable';
my @listing = ( sort { $freq{$b} <=> $freq{$a} } keys %freq)[0..5];
foreach my $word ( @listing )
{
print $freq{$word}." $word\n";
};
产出2:
5 pp
4 kk
4 mm
1 pp.
1 to
1 kkkk
单词mm
,kk
的频率为4-但每次运行时,顺序都会发生变化
我希望输出保持不变
我如何才能基于这样的情况进行排序
关于,,
Ram。对,这里的问题是-您试图对两个没有相对顺序的值进行排序 因此,您的结果基于
键
的返回顺序,根据定义,这是随机的(ish)。就排序而言,这两者是等价的,因此它们以哪种方式出现无关紧要
如果多次运行keys%freq
,将获得不同的键顺序。由于有时kk
会出现在mm
之前,而且就sort
而言,它们是相同的,因为它们具有相同的频率,这就是为什么你会得到你所做的
所以,您需要的是一个二级排序顺序,这样它是一致的。例如,如果频率相同,则按字母顺序排序
有用的-我们可以使用
与|
运算符组合的事实,让您可以链接条件。因为如果你这样做了
$condition1 || $condition2;
如果为“true”,则返回条件1;如果为false,则返回条件2
返回1
、0
或-1
。此处只有0
为false,因此您可以执行以下操作:
$a <=> $b || $a cmp $b
$a$b | |$a$b
或者在您的情况下:
$freq{$b} <=> $freq{$a} || $a cmp $b
$freq{$b}$freq{$a}| |$a cmp$b
像这样:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
my @words = qw ( mm mm mm mm kk kk kk kkkk kk To pp pp pp pp pp pp nn nn );
my %freq;
$freq{$_}++ for @words;
print Dumper \%freq;
foreach my $word ( sort { $freq{$b} <=> $freq{$a}
|| $a cmp $b } keys %freq ) {
print "$word => $freq{$word}\n";
}
#/usr/bin/env perl
严格使用;
使用警告;
使用数据::转储程序;
my@words=qw(mm mm mm kk kk kk kk到pp pp nn);
我的%freq;
@words的$freq{$}++;
打印转储程序\%freq;
foreach my$word(排序{$freq{$b}$freq{$a}
||$a cmp$b}密钥%freq){
打印“$word=>$freq{$word}\n”;
}
这将首先按频率排序,如果有两个具有相同频率,则将按字母数字排序。所以kk=>4
总是在mm=>4
之前订购
您还应在代码中注意:
- 您没有声明
-您应该这样做。您还应该打开%freq
使用strict代码>和
会告诉你这件事的使用警告
使用排序“稳定”代码>似乎什么都没做。这并不奇怪,因为
工作得很好sort
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
my @words = qw ( mm mm mm mm kk kk kk kkkk kk To pp pp pp pp pp pp nn nn );
my %freq;
$freq{$_}++ for @words;
print Dumper \%freq;
foreach my $word ( sort { $freq{$b} <=> $freq{$a}
|| $a cmp $b } keys %freq ) {
print "$word => $freq{$word}\n";
}