11

这是一个小例子:

reg = ur"((?P<initial>[+\-])(?P<rest>.+?))$"

(在这两种情况下,文件都有-*- coding: utf-8 -*-

在 Python 2 中:

re.match(reg, u"hello").groupdict()
# => {u'initial': u'\ud83d', u'rest': u'\udc4dhello'}
# unicode why must you do this

而在 Python 3 中:

re.match(reg, "hello").groupdict()
# => {'initial': '', 'rest': 'hello'}

上述行为是 100% 完美的,但目前还不能切换到 Python 3。将 3 的结果复制到 2 中的最佳方法是什么,它适用于窄 Python 构建和宽 Python 构建?似乎以“\ud83d\udc4d”的格式出现在我面前,这就是让这件事变得棘手的原因。

4

4 回答 4

5

在 Python 2 窄版本中,非 BMP 字符是两个代理代码点,因此您无法在[]语法中正确使用它们。 u'[]等同于u'[\ud83d\udc4d]',表示“匹配或之一 。Python 2.7 示例:\ud83d\udc4d

>>> u'\U0001f44d' == u'\ud83d\udc4d' == u''
True
>>> re.findall(u'[]',u'')
[u'\ud83d', u'\udc4d']

要在 Python 2 和 3 中修复,请匹配u'OR [+-]。这将在 Python 2 和 3 中返回正确的结果:

#coding:utf8
from __future__ import print_function
import re

# Note the 'ur' syntax is an error in Python 3, so properly
# escape backslashes in the regex if needed.  In this case,
# the backslash was unnecessary.
reg = u"((?P<initial>|[+-])(?P<rest>.+?))$"

tests = u'hello',u'-hello',u'+hello',u'\\hello'
for test in tests:
    m = re.match(reg,test)
    if m:
        print(test,m.groups())
    else:
        print(test,m)

输出(Python 2.7):

hello (u'\U0001f44dhello', u'\U0001f44d', u'hello')
-hello (u'-hello', u'-', u'hello')
+hello (u'+hello', u'+', u'hello')
\hello None

输出(Python 3.6):

hello ('hello', '', 'hello')
-hello ('-hello', '-', 'hello')
+hello ('+hello', '+', 'hello')
\hello None
于 2018-01-20T14:33:54.857 回答
3

这是因为 Python2 不区分字节和 unicode 字符串。

请注意,Python 2.7 解释器将字符表示为 4 个字节。要在 Python 3 中获得相同的行为,您必须将 unicode 字符串显式转换为字节对象。

# Python 2.7
>>> s = "hello"
>>> s
'\xf0\x9f\x91\x8dhello'

# Python 3.5
>>> s = "hello"
>>> s
'hello'

因此对于 Python 2,只需使用该字符的十六进制表示作为搜索模式(包括指定长度),它就可以工作。

>>> reg = "((?P<initial>[+\-\xf0\x9f\x91\x8d]{4})(?P<rest>.+?))$"
>>> re.match(reg, s).groupdict()
{'initial': '\xf0\x9f\x91\x8d', 'rest': 'hello'}
于 2018-01-16T06:43:52.263 回答
3

只需单独使用u前缀即可。

在 Python 2.7 中:

>>> reg = u"((?P<initial>[+\-])(?P<rest>.+?))$"
>>> re.match(reg, u"hello").groupdict()
{'initial': '', 'rest': 'hello'}
于 2018-01-16T06:32:52.207 回答
1

在 python 2.7 中有一个选项可以将该 unicode 转换为表情符号:

b = dict['vote'] # assign that unicode value to b 
print b.decode('unicode-escape')

我不知道这正是您要寻找的。但我认为您可以使用它以某种方式解决该问题。

于 2018-01-16T06:29:47.267 回答