在 Python 中,如何替换字符串中的所有非 UTF-8 字符?

dav*_*les 5 python mysql encoding utf-8

更新:真正的问题是 MySQL utf8 不支持四字节 UTF-8 字符。

关于这个主题有几个问题,但似乎没有一个完全是我的问题,除了这个,接受的答案对我不起作用。

我正在使用该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()
Run Code Online (Sandbox Code Playgroud)

它目前产生这个警告:

./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))
Run Code Online (Sandbox Code Playgroud)

当我使用mysql命令行客户端查看实际进入数据库的内容时,我看到内容在第一次出现时被截断非 UTF-8 四字节 UTF-8 字符。

我不在乎保存 非 UTF-8 四字节的 UTF-8 字符,所以我想做的就是全部替换 非 UTF-8 四字节 UTF-8 字符和其他一些有效的 UTF-8 字符,所以我可以将文本放入数据库中。

cyr*_*ril 2

您可以使用正则表达式来删除非 ASCII 字符吗?使用评论中的示例:

\n\n
>>> entry = \'Cognates include Hittite  \xe2\x80\x8e(l\xc4\x81man)\'\n>>> entry = \'\'.join([char if ord(char) < 128 else \'\' for char in entry])\n>>> print entry\nCognates include Hittite  (lman)\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是这个答案的轻微变化这是针对不同问题的

\n