Arrays Perl-捕获数组中出现超过1个元素的句子

Arrays Perl-捕获数组中出现超过1个元素的句子,arrays,perl,Arrays,Perl,我有一个文本文件和一个包含单词列表的数组。我需要找到一种方法,可以过滤出出现次数超过1的句子。我只是不知道如何编写代码。以下是一个例子: 输入: 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 possible", "to find a solution to this

我有一个文本文件和一个包含单词列表的数组。我需要找到一种方法,可以过滤出出现次数超过1的句子。我只是不知道如何编写代码。以下是一个例子:

输入:

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 possible",
    "to find a solution to this problem",
    "i will try my best for a way to this problem"
);

my @words = ("find", "two", "way");
输出:

i'm going to find the occurrence of two words if possible
i'm going to find the occurrence of two words if possible

我明白这是一个简单的问题,但我的思维似乎遇到了障碍。

如果您想要包含两个或多个关键字实例的字符串:

my @keywords = ("find", "two", "way");
my %keywords = map { $_ => 1 } @keywords;

for my $string (@strings) {
   my @words = $string =~ /\w+/g;
   my $count = grep { $keywords{$_} } @words;   # Count words that are keywords.
   if ($count >= 2) {
      ...
   }
}
my @keywords = ("find", "two", "way");

for my $string (@strings) {
   my @words = $string =~ /\w+/g;
   my %seen; ++$seen{$_} for @words;
   my $count = grep { $seen{$_} } @keywords;   # Count keywords that were seen.
   if ($count >= 2) {
      ...
   }
}
短路交替(即适用于极长串):


如果需要包含两个或多个关键字实例的字符串:

my @keywords = ("find", "two", "way");
my %keywords = map { $_ => 1 } @keywords;

for my $string (@strings) {
   my @words = $string =~ /\w+/g;
   my $count = grep { $keywords{$_} } @words;   # Count words that are keywords.
   if ($count >= 2) {
      ...
   }
}
my @keywords = ("find", "two", "way");

for my $string (@strings) {
   my @words = $string =~ /\w+/g;
   my %seen; ++$seen{$_} for @words;
   my $count = grep { $seen{$_} } @keywords;   # Count keywords that were seen.
   if ($count >= 2) {
      ...
   }
}
备选方案:

my @keywords = ("find", "two", "way");

for my $string (@strings) {
   my @words = $string =~ /\w+/g;
   my %seen = map { $_ => -1 } @keywords;
   my $count = grep { ++$seen{$_} == 0 } @words;
   if ($count >= 2) {
      ...
   }
}
短路交替(即适用于极长串):


是否匹配
find-find
?理想情况下,它应该匹配'find'和'two',但'find'和'find'也可能是合理的。这是一个是或否类型的问题…是的,这就是答案,然后您需要包含两个或多个关键字实例的字符串。好的,我可以再查询一次标签\Q和\E,因为在我的数组中可能有也需要匹配。我这样问是因为我必须转义特殊字符,所以才需要查询。我不知道这如何回答我的问题。我猜你不是在问你是否有能力使用
\Q
\E
,我猜你也不是在问你是否有可能使用
\Q
\E
(在每个程序中都可以使用它们),所以我猜你是在问你是否应该使用
\Q
\E
,这将完全取决于你打算如何使用它们。好的,我不知道把它们放在哪里,但我的数组也会有像‘我是’或‘可能不是’或‘要成为’这样的字符串。现在要匹配包含数组元素的句子,我使用的是:if(any{$line=~/\Q$\u\E/}@names){print…}