更新:真正的问题是 MySQL utf8 不支持四字节 UTF-8 字符。
关于这个话题有几个问题,但似乎没有一个是我的问题,除了可能 this one ,其中接受的答案对我不起作用。
我正在使用 MySQLdb
模块在 Python 中进行编码,我想将一些文本放入 MySQL 数据库中。数据库配置为 UTF-8,但文本偶尔包含非 UTF-8 四字节 UTF-8 字符。
修改数据库的 Python 代码如下所示:
connection = MySQLdb.connect(
'localhost',
'root',
'',
'mydatabase',
charset='utf8',
use_unicode=True)
cursor = connection.cursor()
cursor.execute(
'update mytable set entryContent=%s where entryName=%s',
(entryContent, entryName))
connection.commit()
它目前产生这个警告:
./myapp.py:233: Warning: Invalid utf8 character string: 'F09286'
(entry, word))
./myapp.py:233: Warning: Incorrect string value: '\xF0\x92\x86\xB7\xF0\x92...' for column 'entry' at row 1
(entryname, entrycontent))
当我使用 mysql
命令行客户端查看实际进入数据库的内容时,我看到内容在第一次出现 non-UTF-8时被截断del> 四字节 UTF-8 字符。
我不关心保留 non-UTF-8 四字节 UTF-8 字符,所以我想做的就是替换所有 non-UTF-8 四字节 UTF-8 字符和一些其他有效的 UTF-8 字符,因此我可以将文本放入数据库。
最佳答案
您需要将表格编码设置为 utf8mb4
以支持 4 字节 UTF-8 编码 - https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html
此外,MySQL 驱动程序支持 Unicode 字符串,因此您应该传递 Unicode 以使您的代码免受编码细节的影响:
例如
cursor.execute(u'update mytable set entryContent=%s where entryName=%s',
(entryContent.decode("utf-8"), entryName.decode("utf-8")))
理想情况下,entryContent
和 entryName
将在您第一次收到它们时在您的代码中较早地解码为 Unicode。例如。打开文件或从网络接收时。
关于python - 在 Python 中,如何替换字符串中的所有非 UTF-8 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36269880/