加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 06:06:49 所属栏目:大数据 来源:网络整理
导读:是否有人可以帮我找到句子中出现的单词?这些单词列在两个不同的数组中,其思路是从句子中找到两个数组中单词的共同出现. 例: #sentence my $string1 = "i'm going to find the occurrence of two words if possible"; my $string2 = "to find a solution to
是否有人可以帮我找到句子中出现的单词?这些单词列在两个不同的数组中,其思路是从句子中找到两个数组中单词的共同出现.

例:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读