如何用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 this problem";

 #arrays

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

如何在perl中编写一个程序来搜索两个单词的共同出现(例如,进入和可能,因为进入@ arr1并且可能是@ arr2 for $string1,这意味着两个单词co出现在第一个句子中)也是同样在第二句中,即$string2(因为解决方案和问题co发生在至少一个数组中),但第三个句子无效,即$string3(因为句子中的单词不在@ arr1中出现).

谢谢

解决方法

照顾字边界不可能不匹配.

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

猜你在找的Perl相关文章