Python与Perl regex中的反斜杠和转义字符

2024-06-16 14:29:50 发布

您现在位置:Python中文网/ 问答频道 /正文

目标是处理NLP中的标记化任务,并将脚本从Perl script移植到这个Python script。在

主要问题是在运行标记器的Python端口时出现的错误反斜杠。在

在Perl中,我们可能需要对单引号和与号进行转义:

my($text) = @_; # Reading a text from stdin

$text =~ s=n't = n't =g; # Puts a space before the "n't" substring to tokenize english contractions like "don't" -> "do n't".

$text =~ s/\'/\'/g;  # Escape the single quote so that it suits XML.

将regex逐字移植到Python中

^{pr2}$

和号的转义以某种方式添加了一个字面反斜杠=(

为了解决这个问题,我可以:

^{3}$

但是,似乎没有转义Python中的单引号,我们也得到了期望的结果:

>>> import re
>>> from six import text_type
>>> sent = text_type("this ain't funny")
>>> escape_singquote = r"\'", r"\'" # escape the left quote for XML
>>> contraction = r"n't", r" n't" # pad a space on the left when "n't" pattern is seen
>>> escape_singquote = r"'", r"'" # escape the left quote for XML
>>> text = sent
>>> for regexp, substitution in [contraction, escape_singquote]:
...     text = re.sub(regexp, substitution, text)
...     print text
... 
this ai n't funny
this ai n't funny

现在这很令人费解。。。在

考虑到上面的上下文,所以问题是在Python中需要对哪些字符进行转义,而在Perl中需要转义哪些字符?Perl和Python中的Regex不是等价的吗?在


Tags: thetext标记forscriptxmlthisleft
1条回答
网友
1楼 · 发布于 2024-06-16 14:29:50

在Perl和Python中,如果要在字符类之外逐字匹配以下regex元字符,则必须转义它们:

{}[]()^$.|*+?\

在字符类中,必须根据以下规则转义元字符2

^{pr2}$

请注意,无论是在字符类内部还是外部,单引号'或与号&都不能转义。在

但是,如果您使用反斜杠来转义非元字符的标点字符(例如,\'相当于regex中的'),那么Perl和Python都会忽略反斜杠。在


您似乎被Python的raw strings绊倒了:

When an 'r' or 'R' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string.

r"\'"是字符串\'(字面反斜杠,字面单引号),而r'\''是字符串\'(字面反斜杠、字面与号等)。在

所以这个:

re.sub(r"\'", r'\'', text)

将所有单引号替换为文本\'。在


总而言之,您的Perl替代品写得更好:

$text =~ s/'/'/g;

你的Python替代品写得更好:

re.sub(r"'", r''', text)

  1. Python2、Python3和Perl的当前版本将非转义大括号视为文本大括号(如果它们不是量词的一部分)。但是,这在Perl的未来版本中将是一个语法错误,最近的Perl版本会发出警告。

  2. 请参见perlretutperlre,以及re module的Python文档。

相关问题 更多 >