匹配同一个单词的不同实例

时间:2012-05-22 21:38:55

标签: perl

如何匹配同一个单词的不同实例。

例如:如果字符串是协同作用。如何与协同作用,协同作用,协同作用,协同作用相匹配。 我可以写下面的内容:

    while(<IN>)
 {
chomp $_;
my $line= $_;
$word="Synergy";
if($line=~m/$word(\w+)/i)
{
     $line=~s/$word/<Effect>$word<\/Effect>/ig;
}
 }

3 个答案:

答案 0 :(得分:3)

你可能想做的事情叫做词干。 但是,要使其工作,您必须阻止文本中的所有单词加上您搜索的单词。希望您列出的所有单词都会产生相同的词干。我还没有测试过它。

use Lingua::Stem;
my $stemmer = Lingua::Stem->new( -locale => 'EN-UK' );

# first convert text to list of words
my @words;
while(<IN>) {
    push @words, split(/\b/, $_); # you can do better here
}
# now stem all words.
my $stemmed_words = $stemmer->stem(@words);
# results in an array ref of stems in the same order as the words have been.

# now stem your search
my $stemmed_search = $stemmer->stem($word);

# and do the search from above inside stemmed array.

现在取决于你想要什么。如果你想用某些东西交换所有这些单词,你必须获得匹配(词干)单词的索引,并在文本内的相同位置进行替换。

答案 1 :(得分:0)

您将要使用正则表达式。目前还不清楚您想要匹配的标准究竟是什么,但在您的示例中,所有单词都以“synergi”开头,因此if($string =~ \bsynergi\w*\b)会在其中的任何位置找到包含“synergi”的所有行。

答案 2 :(得分:0)

您可能想查看Text :: Soundex。例如,

use Text::Soundex;

# The following all return S562
print soundex("synergizes"), "\n";
print soundex("synergism"), "\n";
print soundex("synergically"), "\n";
print soundex("synergistic"), "\n";

进一步阅读:Perldoc Text::Soundex