0

我有一个带有各种关键字的哈希。现在,我想在字符串中找到这些关键字的计数。

我刚刚用 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

有人可以帮助我吗?

谢谢

4

3 回答 3

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";
}
于 2012-09-17T19:06:37.067 回答
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";
}
于 2012-09-17T19:17:01.603 回答
0

那是家庭作业吗?:) 好吧,取决于散列中的单词数和字符串(字符串)中的单词数,它会更好地迭代散列,或者迭代字符串中的单词,找到时增加适当的值。由于您需要检查所有单词,因此您将以一个列表结尾,其中一些标记为“0”,一些标记为大于零。

于 2012-09-17T18:25:24.223 回答