上下文,我正在尝试从https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/normalize-punctuation.perl#L87将Perl代码移植到Python中,并且Perl中有此正则表达式:
s/(\d) (\d)/$1.$2/g;
如果使用给定输入文本123 45
的Perl脚本进行尝试,它将返回带有点的相同字符串。作为健全性检查,我也在命令行上尝试过:
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
但是当我使用Moses脚本时:
$ 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
即使我们尝试在Moses code中的正则表达式之前和之后打印字符串,即
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
我们看到正则表达式前后,字符串没有变化。
我的问题部分是:
\g<1>.\g<2>
正则表达式是否等同于Perl的$1.$2
?.
? 答案 0 :(得分:3)
moose的此代码不起作用的原因是,它搜索的是不间断的空间,而不仅仅是空间。这不容易看到,但是hexdump
可以帮助您:
fe-laptop-p:moose fe$ head -n87 normalize-punctuation.perl | tail -n1 | hexdump -C
00000000 09 73 2f 28 5c 64 29 c2 a0 28 5c 64 29 2f 24 31 |.s/(\d)..(\d)/$1|
00000010 2e 24 32 2f 67 3b 0a |.$2/g;.|
00000017
fe-laptop-p:moose fe$ head -n87 normalize-punctuation.perl.with_space | tail -n1 | hexdump -C
00000000 09 73 2f 28 5c 64 29 20 28 5c 64 29 2f 24 31 2e |.s/(\d) (\d)/$1.|
00000010 24 32 2f 67 3b 0a |$2/g;.|
00000016
看到区别:c2 a0
与20
?
p.s。 至于在正则表达式中添加加号的注释:此处不需要,因为足以在两个相邻数字之间放置点号,而无需查找完整数字