gpt4 book ai didi

Python,转换4字节字符以避免MySQL错误 "Incorrect string value:"

转载 作者:太空狗 更新时间:2023-10-29 21:22:42 26 4
gpt4 key购买 nike

我需要将(在 Python 中)一个 4 字节的字符转换成其他字符。这是为了将它插入到我的 utf-8 mysql 数据库中而不会出现错误,例如:“不正确的字符串值:'\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)构建。但是我不清楚该怎么做?

最佳答案

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

关于Python,转换4字节字符以避免MySQL错误 "Incorrect string value:",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12636489/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com