2011-12-13 2 views
1

이 방법 이외의 단어를 매치하는 더 좋은 방법은, 문장에서 발생하는 단어를 배열에서 찾으려고하는 것입니다.Perl을 사용하여 문장에서 순차적 단어를 찾는 방법은 무엇입니까?

my $count = 0; 
my @strings = (
    "i'm going to find the occurrence of two words going if possible", 
    "i'm going to find the occurrence of two words if impossible", 
    "to find a solution to this problem", 
    "i will try my best for a way to match this problem" 
); 
@neurot = qw(going match possible); 

my $com_neu = '\b'.join('\b|\b', @neurot).'\b'; 

foreach my $sentence (@string){ 

@l = $sentence =~ /($com_neu)/gi; 

foreach my $list (@l){ 
    if($list =~ m/\w['\w-]*/){ 
      print $list; 
     $count++; 
    } 
} 

print $count; 
} 

출력 :

String 1: going going possible 
String 2: going 
String 3: 
String 4: match 

는 빠른 방법으로 저를 도와주세요.

감사합니다.

+2

아마 청소기, 필요하지 않은'\ b' 단지 괄호 주위의 모든 단어, 주위 : '\ B를 ($ com_neu) \ b'. – TLP

+1

데이터와 문장 ('@ neurot '의 단어 수, 문장의 길이 ...)에 대한 정보를 제공해야합니다. – bvr

+1

m/\ w /는 m/\ w [ '\ w -] */will과 동일한 문자열을 모두 찾습니다. 그렇다면 [ '\ w -] * 부분의 요점은 무엇입니까? – tadmc

답변

1

또 다른 방법은 단어와 일치하는 해시를 사용하는 것이 될 수있다 :이 방법을 제공하는 데이터의

my %neurot_hash = map { lc($_) => 1 } qw(going match possible); 

for my $sentence (@strings) { 
    for my $found (grep { $neurot_hash{ lc($_) } } $sentence =~ /\w['\w-]*/gi) { 
     print $found, " "; 
    } 
    print "\n"; 
} 

7 % 빠른 ~입니다. 그러나 데이터 세트는 매우 작으므로 YMMV를 명심하십시오.

1

'스마트 매치'연산자는 어떻습니까?

foreach my $elem (@neurot){ if(/$elem/i ~~ @strings){ print "Found $elem\n"; } }

+0

이렇게하면 어떤 문자열에 어떤 요소가 들어 있는지 말할 수 없게됩니다. 또한, '@ neurot'이 일종의 사전이라면, 이것은 아주 비효율적 일 수 있습니다. – bvr

+0

@bvr : 네가 맞아'@ neurot'은 사전이야. 비효율적이다. – aliocee

0

BVR 응답과 동일하지만, 우선 들어

my %neurot_hash = map { lc($_) => 1 } qw(going match possible); 

for my $sentence (@strings) { 
    my @words = split /[^\w']/, $sentence; 
      #I am not sure if you want to take "i'm" as a separate word. 
      #Apparently, stackoverflow does not like '. 

    my @found = grep { exists $neurot_hash{ lc($_) } } @words; 
    print join (" ", @found); 
    print "\n"; 
} 
관련 문제