2012-09-17 90 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"; 
}