限制翻译为短语中的一个词?

3

我从Python转到Perl世界,想知道是否有一种简单的方法来将翻译或替换限制在短语中的一个词上?

在这个例子中,第二个单词kind也被改成了lind。是否有一种简单的方法可以进行翻译而不需要涉及循环?谢谢。

第一个单词已经被正确翻译为gazelle,但是第二个单词也被更改了,如您所见。


my $string = 'gazekke is one kind of antelope';

my $count = ($string =~ tr/k/l/);

print "There are $count changes \n";

print $string;         # gazelle is one lind of antelope    <-- kind becomes lind too!
3个回答

2
我不知道有没有选项可以让tr在第一个单词后停止翻译。但你可以使用带反向引用的正则表达式来实现此目的。
use strict;

my $string = 'gazekke is one kind of antelope';

# Match first word in $1 and rest of sentence in $2.
$string =~ m/(\w+)(.*)/;

# Translate all k's to l's in the first word.
(my $translated = $1) =~ tr/k/l/;

# Concatenate the translated first word with the rest
$string = "$translated$2";

print $string;

输出:瞪羚是一种羚羊

2

在没有使用/g的情况下,精确地选择第一个匹配项(在本例中是一个单词),这正是正则表达式的作用,并在该单词中通过运行替换代码,在替换侧替换所有所需字符,使用/e

$string =~ s{(\w+)}{ $1 =~ s/k/l/gr }e;

在替换的正则表达式中,/r 修饰符使其方便地返回更改后的字符串,并且不更改原始字符串,这也允许在 $1 上运行替换(因为它是只读的,不能修改)。

0

tr 是一个字符类转换器。对于其他任何东西,您都可以使用正则表达式。

$string =~ s/gazekke/gazelle/;

您可以将代码块作为 s/// 的第二部分,以执行更复杂的替换或变形。

$string =~ s{([A-Za-z]+)}{ &mangler($1) if $should_be_mangled{$1}; }ge;

编辑: 以下是如何首先定位短语,然后处理它。

$phrase_regex = qr/(?|(gazekke) is one kind of antelope|(etc))/;
$string =~ s{($phrase_regex)}{
  my $match = $1;
  my $word = $2;
  $match =~ s{$word}{
    my $new = $new_word_map{$word};
    &additional_mangling($new);
    $new;
  }e;
  $match;
}ge;



这是Perl正则表达式文档。 https://perldoc.perl.org/perlre

谢谢!我知道trs之间的区别。问题/挑战是处理一个短语,而不是单个单词。 - Daniel Hao
你能详细解释一下吗?如果你需要挑选一个短语并且再选出一个单词进行更改,你可以通过嵌套正则表达式来实现。 - lordadmira

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接