获取Perl中的nbest键值对哈希表
我有一个使用哈希表的脚本:获取Perl中的nbest键值对哈希表,perl,sorting,hash,hashtable,perl-data-structures,Perl,Sorting,Hash,Hashtable,Perl Data Structures,我有一个使用哈希表的脚本: #!/usr/bin/env perl use strict; use warnings; my $hash = { 'cat' => { "félin" => '0.500000', 'chat' => '0.600000', 'chatterie' => '0.300000' 'chien' => '
#!/usr/bin/env perl
use strict; use warnings;
my $hash = {
'cat' => {
"félin" => '0.500000',
'chat' => '0.600000',
'chatterie' => '0.300000'
'chien' => '0.01000'
},
'rabbit' => {
'lapin' => '0.600000'
},
'canteen' => {
"ménagère" => '0.400000',
'cantine' => '0.600000'
}
};
my $text = "I love my cat and my rabbit canteen !\n";
foreach my $word (split "\s+", $text) {
print $word;
exists $hash->{$word}
and print "[" . join(";", keys %{ $hash->{$word} }) . "]";
print " ";
}
目前,我有以下输出:
I love my cat[chat;félin;chatterie;chien] and my rabbit[lapin] canteen[cantine;ménagère] !
我需要根据频率(存储在我的散列中)获得nbest键值。例如,我希望根据以下频率获得3个最佳翻译:
I love my cat[chat;félin;chatterie] and my rabbit[lapin] canteen[cantine;ménagère] !
如何更改代码以考虑每个值的频率并打印nbest值
感谢您的帮助。最整洁的方法是编写一个子程序,返回给定单词的N个最频繁的翻译。为了做到这一点,我在下面的程序中编写了
best\n
。它使用rev\u sensort\u by
from简洁地进行排序。它不是核心模块,因此可能需要安装
我还使用了一个可执行替换来就地修改字符串
use utf8;
use strict;
use warnings;
use List::UtilsBy qw/ rev_nsort_by /;
my $hash = {
'cat' => {
'félin' => '0.500000',
'chat' => '0.600000',
'chatterie' => '0.300000',
'chien' => '0.01000',
},
'rabbit' => {
'lapin' => '0.600000',
},
'canteen' => {
'ménagère' => '0.400000',
'cantine' => '0.600000',
}
};
my $text = "I love my cat and my rabbit canteen !\n";
$text =~ s{(\S+)}{
$hash->{$1} ? sprintf '[%s]', join(';', best_n($1, 3)) : $1;
}ge;
print $text;
sub best_n {
my ($word, $n) = @_;
my $item = $hash->{$word};
my @xlate = rev_nsort_by { $item->{$_} } keys %$item;
$n = $n > @xlate ? $#xlate : $n - 1;
@xlate[0..$n];
}
输出
I love my [chat;félin;chatterie] and my [lapin] [cantine;ménagère] !
对键进行数字排序?是,根据散列信息自然排序。例如,第一个条目:1)chat 2)félin 3)chatterie 4)chien。然后,在我的例子中,我想得到3个最佳值。在这个例子中,输出是
[chien;chatterie;félin]
,但根据频率的nbest是[chat;félin;chatterie]
。在子程序中可能有一件事需要改变才能解决这个问题?@切斯特:一个愚蠢的错误:我按频率递增的顺序对单词进行排序,并取前三个,因此频率最低。同一模块提供了一个按降序排序的rev\u sensort\u by
,并修复了该问题。