如何用perl在句子中找到单词的共同出现?

时间:2011-09-21 23:26:40

标签: perl

有没有人可以帮我找到句子中出现的单词?这些单词列在两个不同的数组中,其思路是从句子中找到两个数组中单词的共同出现。

示例:

 #sentence

 my $string1 = "i'm going to find the occurrence of two words if possible";
 my $string2 = "to find a solution to this problem";
 my $string3 = "i will try my best for a way to this problem";

 #arrays

 my @arr1 = qw(i'm going match possible solution);
 my @arr2 = qw(problem possible best);

如何在perl中编写程序以搜索两个单词的共同出现(例如正在可能,因为正在进行是在@arr1可能位于@arr2 $string1,这意味着两个单词在第一个句子中出现)在第二个句子中也是相同的,即{{1} }(因为解决方案问题 co发生在至少一个数组中)但第三个句子无效,即$string2(因为非{句子出现在$string3)。

谢谢

2 个答案:

答案 0 :(得分:4)

#!/usr/bin/perl
use warnings;
use strict;

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

my @arr1 = qw(going match possible solution);
my @arr2 = qw(problem possible best);

my $pat1 = join '|', @arr1;
my $pat2 = join '|', @arr2;

foreach my $str (@strings) {
    if ($str =~ /$pat1/ and $str =~ /$pat2/) {
        print $str, "\n";
    }
}

答案 1 :(得分:3)

照顾字边界与possible中的impossible不匹配。

#!/usr/bin/perl
use Modern::Perl;

my @strings = (
    "i'm going to find the occurrence of two words 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 this problem"
);

my @arr1 = qw(i'm going match possible solution);
my @arr2 = qw(problem possible best);

my $re1 = '\b'.join('\b|\b', @arr1).'\b';
my $re2 = '\b'.join('\b|\b', @arr2).'\b';

foreach my $str (@strings) {
    my @l1 = $str =~ /($re1)/g;
    my @l2 = $str =~ /($re2)/g;
    if (@l1 && @l2) {
        say "found : [@l1] [@l2] in : '$str'";
    } else {
        say "not found in : '$str'";
    }
}

<强>输出:

found : [i'm going possible] [possible] in : 'i'm going to find the occurrence of two words if possible'
not found in : 'i'm going to find the occurrence of two words if impossible'
found : [solution] [problem] in : 'to find a solution to this problem'
not found in : 'i will try my best for a way to this problem'