我有一个包含各种关键字的哈希。现在,我想在字符串中找到这些关键字的计数。
我刚用foreach循环编写了部分代码。
use strict;
use warnings;
my $string = "The invitro experiments are conducted on human liver microsom. "
. " These liver microsom can be cultured in rats.";
my %hash = (
"human" => 1,
"liver" => 1,
"microsom" => 1,
);
for my $nme (keys %hash){
# Some code which I am not sure
}
预期输出:human:1; liver:2; microsom:3
有人可以帮助我吗?
由于
答案 0 :(得分:1)
以下代码段就足够了。
#!/usr/bin/perl -w
use strict;
my $string="The invitro experiments are conducted on human liver microsom. These liver microsom can be cultured in rats.";
my %hash = (
'human' => 1,
'liver' => 1,
'microsom' => 1,
);
my @words = split /\b/, $string;
my %seen;
for (@words) {
if ($_ eq 'human' or $_ eq 'liver' or $_ eq 'microsom') {
$seen{$_}++;
}
}
for (keys %hash) {
print "$_: $seen{$_}\n";
}
答案 1 :(得分:0)
那是家庭作业吗? :)嗯,取决于散列中的单词数和字符串(字符串)中的单词数,它将更好地迭代哈希,或迭代字符串中的单词,在找到时递增适当的值。当您需要检查所有单词时,您将以一个标记为“0”的列表结束,有些标记为大于零。
答案 2 :(得分:0)
可能不是解决此问题的最佳方式,但它应该有效。
my $string = "The invitro experiments are conducted on human liver microsom. These liver microsom can be cultured in rats.";
my %hash = (
'human' => 1,
'liver' => 1,
'microsom' => 1,
);
foreach my $nme (keys %hash){
$hash{$nme} = scalar @{[$string =~ /$nme/g]};
print "$hash{$nme}\n";
}