上下文,我正在尝试将 Perl 代码从https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/normalize-punctuation.perl#L87移植到 Python 中,这里有这个正则表达式珀尔:
s/(\d) (\d)/$1.$2/g;
如果我在给定输入 text 的 Perl 脚本中尝试它123 45
,它会返回带有点的相同字符串。作为健全性检查,我也在命令行上尝试过:
echo "123 45" | perl -pe 's/(\d) (\d)/$1.$2/g;'
[出去]:
123.45
当我将正则表达式转换为 Python 时也是如此,
>>> import re
>>> r, s = r'(\d) (\d)', '\g<1>.\g<2>'
>>> print(re.sub(r, s, '123 45'))
123.45
但是当我使用摩西脚本时:
$ wget https://raw.githubusercontent.com/moses-smt/mosesdecoder/master/scripts/tokenizer/normalize-punctuation.perl
--2019-03-19 12:33:09-- https://raw.githubusercontent.com/moses-smt/mosesdecoder/master/scripts/tokenizer/normalize-punctuation.perl
Resolving raw.githubusercontent.com... 151.101.0.133, 151.101.64.133, 151.101.128.133, ...
Connecting to raw.githubusercontent.com|151.101.0.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 905 [text/plain]
Saving to: 'normalize-punctuation.perl'
normalize-punctuation.perl 100%[================================================>] 905 --.-KB/s in 0s
2019-03-19 12:33:09 (8.72 MB/s) - 'normalize-punctuation.perl' saved [1912]
$ echo "123 45" > foobar
$ perl normalize-punctuation.perl < foobar
123 45
即使我们尝试在摩西代码中的正则表达式之前和之后打印字符串,即
if ($language eq "de" || $language eq "es" || $language eq "cz" || $language eq "cs" || $language eq "fr") {
s/(\d) (\d)/$1,$2/g;
}
else {
print $_;
s/(\d) (\d)/$1.$2/g;
print $_;
}
[出去]:
123 45
123 45
123 45
我们看到在正则表达式之前和之后,字符串没有变化。
我的部分问题是:
- Python
\g<1>.\g<2>
正则表达式是否等同于 Perl 的$1.$2
? - 为什么 Perl 正则表达式没有
.
在 Moses 的两位数组之间添加句号? - 如何在 Python 正则表达式中复制 Perl 在 Moses 中的行为?
- 如何在摩西的 Perl 正则表达式中复制 Python 的行为?