首页 > 解决方案 > perl 正则表达式之间的区别在摩西的两个数字之间添加点

问题描述

上下文,我正在尝试将 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

我们看到在正则表达式之前和之后,字符串没有变化。

我的部分问题是:

标签: pythonregexperlnlpmoses

解决方案


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 a0vs 20?

ps关于在正则表达式中添加加号的评论:这里不需要,因为在两个相邻数字之间放置点号就足够了,不需要找到完整的数字


推荐阅读