Python删除Unicode字符串中的iOS表情符号,避免DatabaseError: Incorrect string value
我有一个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
可能是问题所在,它们是一种特殊的图像代码。那么,怎么才能检测到这样的字符串并把它们去掉呢?
1 个回答
6
我在这里找到了答案:这里。
关于表情符号的信息可以查看这个链接: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'
这段代码有效!