如何使用perl查找句子中的单词共现?

如何使用perl查找句子中的单词共现?,perl,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 thi

有没有人能帮我找到一个句子中单词的共现?单词被列在两个不同的数组中,目的是从句子中找出两个数组中单词的共现

例如:

 #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编写一个程序来搜索两个单词的同时出现(例如,goingObable,因为going
@arr1
中,而Obable
@arr2
中,这意味着这两个单词同时出现在第一句话中)第二句同样如此,即
$string2
(因为解决方案问题至少在一个数组中同时出现),但第三句是无效的,即
$string3
(因为句子中没有任何单词出现在
@arr1


谢谢

注意在
不可能
中单词边界不匹配
可能

#!/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";
    }
}
#!/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'

非常感谢,如果我想知道句子中匹配的单词的数量,比如数组元素的不止一次出现,我该如何处理带有标点符号的单词呢?不能t@aliocee当前位置不太确定我是否理解您的第一条评论,但我已更新了我的答案。对于像
i'm
这样的词,只需将它们添加到数组中即可。这意味着我如何使用以下内容处理数组:
@arr1=(“我要去”、“匹配”、“可能的”解决方案)这意味着第一个元素包含2个单词?