首页 > 解决方案 > 由于mysql数据中的无效延续字节如何捕获UnicodeDecodeError

问题描述

我正在将数千万行文本数据从 mysql 移动到搜索引擎,并且无法成功处理检索到的字符串之一中的 Unicode 错误。我尝试对检索到的字符串进行显式编码和解码,以使 Python 抛出 Unicode 异常并了解问题所在。

在我的笔记本电脑上运行了数千万行之后抛出了这个异常(叹息......),但我无法捕捉到它,跳过那一行并继续我想要的。mysql 数据库中的所有文本都应该是 utf-8。

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 143: invalid continuation byte

这是我使用Mysql Connector/Python建立的连接

cnx = mysql.connector.connect(user='root', password='<redacted>',
                          host='127.0.0.1',
                          database='bloggz',
                          charset='utf-8') 

下面是数据库字符设置:

mysql> SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR 
Variable_name LIKE 'collation%';

+-------------------------+------------------+

| 变量名 | 价值 |

+-------------------------+------------------+

| character_set_client | utf8 |

| 字符集连接 | utf8 |

| 字符集数据库 | utf8 |

| 字符集文件系统 | 二进制 |

| 字符集结果 | utf8 |

| character_set_server | utf8 |

| 字符集系统 | utf8 |

| collat​​ion_connection | utf8_general_ci |

| collat​​ion_database | utf8_general_ci |

| 排序服务器 | utf8_general_ci |

+-------------------------+------------------+

下面我的异常处理有什么问题?请注意,变量“last_feeds_id”也没有打印出来,但这可能只是证明 except 子句不起作用。

last_feeds_id = 0
for feedsid, ts, url, bid, title, html in cursor:

  try:
    # to catch UnicodeErrors and see where the prolem lies
    # from: https://mail.python.org/pipermail/python-list/2012-July/627441.html
    # also see https://stackoverflow.com/questions/28583565/str-object-has-no-attribute-decode-python-3-error

    # feeds.URL is varchar(255) in mysql
    enc_url = url.encode(encoding = 'UTF-8',errors = 'strict')
    dec_url = enc_url.decode(encoding = 'UTF-8',errors = 'strict')

    # texts.title is varchar(600) in mysql
    enc_title = title.encode(encoding = 'UTF-8',errors = 'strict')
    dec_title = enc_title.decode(encoding = 'UTF-8',errors = 'strict')

    # texts.html is text in mysql
    enc_html = html.encode(encoding = 'UTF-8',errors = 'strict')
    dec_html = enc_html.decode(encoding = 'UTF-8',errors = 'strict')

    data = {"timestamp":ts,
            "url":dec_url,
           "bid":bid,
           "title":dec_title,
           "html":dec_html}
    es.index(index="blogposts",
            doc_type="blogpost",
            body=data)
  except UnicodeDecodeError as e:
    print("Last feeds id: {}".format(last_feeds_id))
    print(e)

  except UnicodeEncodeError as e:
    print("Last feeds id: {}".format(last_feeds_id))
    print(e)

  except UnicodeError as e:
    print("Last feeds id: {}".format(last_feeds_id))
    print(e)

标签: mysqlpython-3.xutf-8mysql-pythonunicode-string

解决方案


它抱怨 hex ED。你期待acute-i:í吗?如果是这样,那么您拥有的文本不是编码 UTF-8,而是 cp1250、dec8、latin1、latin2、latin5 之一。

你的 Python 源代码是否以

# -*- coding: utf-8 -*-

查看更多 Python-utf8 提示

此外,请在此处查看“最佳实践”

你有charset='utf-8'; 我不确定,但也许应该是这样charset='utf8'引用 UTF-8就是世人所说的字符集。MySQL 称其为 3 字节子集utf8。注意没有破折号。


推荐阅读