【问题标题】:How to detect and duplicate word co-occurence in a sentence in Perl?如何在 Perl 中检测和复制句子中的单词共现?
【发布时间】:2011-12-12 13:02:53
【问题描述】:

我有一组单词,我有兴趣根据两个或多个单词的出现来查找句子的重复项:

例子:

我想检测句子中的“男孩”或“男孩”和“女孩”或“女孩”,这样我就可以拥有这些集合:(男孩和女孩)、(男孩和女孩)、(女孩和男孩) ) 和 (男孩和女孩)。

句子:

男孩要和一个女孩一起上学,因为男孩非常喜欢女孩

句子表示:

WORD1带着WORD2去上学,因为WORD3太喜欢WORD4了。

我怎样才能有四 (4) 种不同形式的句子,使它看起来像这样:

输出:

The WORD1 is going to school with a WORD2, because the WORD like the WORD so much.
The WORD1 is going to school with a WORD, because the WORD like the WORD4 so much.
The WORD is going to school with a WORD2, because the WORD3 like the WORD so much.
The WORD is going to school with a WORD, because the WORD3 like the WORD4 so much.

注意。

字数可以是动态的,从2个或更多;在这个例子中,我有 4 个单词。

【问题讨论】:

  • 一种方法是为每个组合设置一个正则表达式。您可以从允许的单词对构建每个正则表达式,然后使用交替 | 运算符将它们连接在一起。
  • @user5402:能给我举个例子吗?
  • 为什么输出包含第五个“WORD”而没有数字后缀?它代表四个输入词中的哪一个?
  • @Jonathan - 'WORD' 只是我用来替换其他成对单词的符号,在新生成的句子中是一个无关紧要的符号。
  • 我不得不说我不是很理解这个问题。你有一个给定的句子,你想用另一组词替换给定的词并形成四个新句子?

标签: perl text


【解决方案1】:

使用反向引用:

if ($sentence =~ m/\b(\w+)\b.*\b\1/) {
  print "repeated use of the word $1\n";
}

【讨论】:

  • 这个语句是否会匹配我在括号中指出的单词对。
  • 我想我没有完全理解原来的问题。
【解决方案2】:

虽然它仍需要大量改进,但以下内容应该可以帮助您入门并指明正确的方向:

#!/usr/bin/env perl

use strict;
use warnings;

use Algorithm::Permute;
use Lingua::EN::Tagger;
use Lingua::EN::Inflect::Number qw(to_S);

my $text = q{The boy is going to school with a girl, because the boys
like the girls so much.};

my $tagger = Lingua::EN::Tagger->new;

my $tagged_text = $tagger->add_tags( $text );

my %nouns = $tagger->get_nouns( $tagged_text );

my %normalized;
for my $noun (keys %nouns) {
    $normalized{ to_S($noun)}{ $noun } = undef;
}

for my $nouns (values %normalized) {
    my $p = Algorithm::Permute->new([ keys %$nouns ]);

    while (my @tuple = $p->next) {
        print join(', ', @tuple), "\n";
    }
}

输出:

男孩,男孩
男孩,男孩
学校
女孩,女孩
女孩,女孩

【讨论】:

    猜你喜欢
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 2020-05-23
    • 2020-04-14
    相关资源
    最近更新 更多