Python,转换4字节字符以避免MySQL错误"字符串值不正确:"

use*_*003 7 python mysql utf-8 character-encoding python-unicode

我需要将(在Python中)一个4字节的char转换为其他字符.这是将其插入到我的UTF-8 mysql数据库没有得到一个错误,如:"不正确的字符串值:在第1行'\ XF0\x9F\X94\x8E’列'线’"

通过向mysql插入4字节unicode引发的警告显示这样做:

>>> import re
>>> highpoints = re.compile(u'[\U00010000-\U0010ffff]')
>>> example = u'Some example text with a sleepy face: \U0001f62a'
>>> highpoints.sub(u'', example)
u'Some example text with a sleepy face: '
Run Code Online (Sandbox Code Playgroud)

但是,我得到了与评论中的用户相同的错误,"...字符范围很差.."这显然是因为我的Python是UCS-2(而不是UCS-4)版本.但后来我不知道该怎么做呢?

Mar*_*ers 15

在UCS-2版本中,python在\U0000ffff代码点上为每个unicode字符内部使用2个代码单元.正则表达式需要与这些表达式一起使用,因此您需要使用以下正则表达式来匹配这些:

highpoints = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]')
Run Code Online (Sandbox Code Playgroud)

此正则表达式匹配使用UTF-16代理对编码的任何代码点(请参阅UTF-16代码点U + 10000到U + 10FFFF.

要使这与Python UCS-2和UCS-4版本兼容,您可以使用try:/ except来使用其中一个:

try:
    highpoints = re.compile(u'[\U00010000-\U0010ffff]')
except re.error:
    # UCS-2 build
    highpoints = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]')
Run Code Online (Sandbox Code Playgroud)

在UCS-2 python构建上演示:

>>> import re
>>> highpoints = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]')
>>> example = u'Some example text with a sleepy face: \U0001f62a'
>>> highpoints.sub(u'', example)
u'Some example text with a sleepy face: '
Run Code Online (Sandbox Code Playgroud)