剛從Python 進入 Perl 世界,想知道是否有一種簡單的方法可以將翻譯或替換為短語中的一個單詞?
在示例中,第二個單詞k ind也更改為l ind。有沒有一種簡單的方法可以在不進行回圈的情況下進行翻譯?謝謝。
如您所見,第一個單詞已正確翻譯為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!
uj5u.com熱心網友回復:
我不知道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;
輸出:gazelle is one kind of antelope
uj5u.com熱心網友回復:
選擇第一個匹配項(在這種情況下是一個單詞),這正是正則運算式在沒有 時所做的事情/g,并且在那個單詞中替換所有想要的字符,通過在替換端運行代碼,通過/e
$string =~ s{(\w )}{ $1 =~ s/k/l/gr }e;
在替換端的正則運算式中,/r修飾符使其輕松回傳更改后的字串并且不更改原始字串,這也允許替換運行$1(不能修改為只讀)。
uj5u.com熱心網友回復:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/506237.html
