2012-09-17 91 views
0

我有一个散列与各种关键字。现在,我想查找字符串中这些关键字的计数。Perl匹配计数

我只是用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

有人可以帮助我在这?

谢谢

+1

why microsom:3? '$ string'中似乎只有两处出现! – Vikdor

+1

你应该在尝试之前[尝试](http://mattgemmell.com/2008/12/08/what-have-you-tried/)。如果你有,告诉我们你的尝试。 – m0skit0

+0

对不起。它应该是microsom:2。 –

回答

0

这是功课吗? :)好吧,取决于散列中的单词数量和字符串中的单词数量(字符串),它将更好地迭代散列,或迭代字符串中的单词,找到时递增适当的值。由于您需要检查所有单词,因此您将以带有一些标记为“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

尝试'split/\ b /,$ string;'分割单词边界。 – RobEarl

+0

编辑,谢谢! –

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"; 
}