python删除unicode str中的IOS表情符号,以避免数据库错误:字符串值不正确

2024-09-30 22:23:32 发布

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

我有一个json {u'nickname':u'\U0001f638\U0001f638\u5bb6\u52c7'}。 将nickname保存到数据库时,将引发:

DatabaseError: (1366, "Incorrect string value: '\\xF0\\x9F\\x98\\xB8\\xF0\\x9F..
.' for column 'nickname' at row 1")

我认为\U0001f638\U0001f638是问题所在,它们是某种图像代码。但是如何检测并移除这些字符串?在


Tags: 数据库jsonforstringvaluenicknamecolumnx98
1条回答
网友
1楼 · 发布于 2024-09-30 22:23:32

我找到了答案here。 表情信息:http://punchdrunker.github.io/iOSEmoji/table_html/index.html

\U0001f638是IOS表情符号。 使用Martijn Pieters的代码:

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

>>> import re
>>> highpoints = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]')
>>> example = u'\U0001f638\U0001f638\u5bb6\u52c7'
>>> highpoints.sub(u'', example)
u'\u5bb6\u52c7'

它起作用了!在

相关问题 更多 >