【问题标题】:Python, convert 4-byte char to avoid MySQL error "Incorrect string value:"Python,转换 4 字节字符以避免 MySQL 错误“不正确的字符串值:”
【发布时间】:2012-09-20 03:08:22
【问题描述】:

我需要(在 Python 中)将 4 字节字符转换为其他字符。这是将其插入到我的 utf-8 mysql 数据库中而不会出现错误,例如:“Incorrect string value: '\xF0\x9F\x94\x8E' for column 'line' at row 1”

Warning raised by inserting 4-byte unicode to mysql 显示这样做:

>>> 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: '

但是,我在评论中遇到与用户相同的错误,“...错误的字符范围..”这显然是因为我的 Python 是 UCS-2(而不是 UCS-4)构建。但后来我不清楚该怎么做?

【问题讨论】:

  • 在MySql中使用utf8mb4 charset还会有问题吗?
  • 不确定。不幸的是,我无法更改数据库的字符集。

标签: python mysql utf-8 character-encoding python-unicode


【解决方案1】:

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

highpoints = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]')

此正则表达式匹配使用 UTF-16 代理对编码的任何代码点(请参阅UTF-16 Code points U+10000 to 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]')

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: '

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 2012-11-08
    • 2020-11-19
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 2018-03-29
    相关资源
    最近更新 更多