python - 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
我们看到在正则表达式之前和之后,字符串没有变化。
我的部分问题是:
- Python
\g<1>.\g<2>
正则表达式是否等同于 Perl 的$1.$2
? - 为什么 Perl 正则表达式没有
.
在 Moses 的两位数组之间添加句号? - 如何在 Python 正则表达式中复制 Perl 在 Moses 中的行为?
- 如何在摩西的 Perl 正则表达式中复制 Python 的行为?
解决方案
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
vs 20
?
ps关于在正则表达式中添加加号的评论:这里不需要,因为在两个相邻数字之间放置点号就足够了,不需要找到完整的数字
推荐阅读
- bootstrap-4 - 使用 Promise 防止关闭 Bootstrap 模式
- angular - 在 ionic 项目中使用 Angular 库时,必须从注入上下文调用 inject()
- telegram - 我的 Telegram Bot 已添加到垃圾邮件频道。如何删除它?
- multithreading - 在 MVVM 架构中使用领域时出现线程错误
- java - springboot中@oneToMany双向映射的问题
- node.js - React 私有路由真的安全吗?
- c# - 数组元素为空,除了第一个
- python - 在 Django 中处理某些 CRUD 异常的正确方法是什么
- c++ - 如何按层次顺序构造二叉树
- java - 将 JavaFX X 和 Y 轴定位在中心