mysql - 由于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 |
| collation_connection | utf8_general_ci |
| collation_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)
解决方案
推荐阅读
- spring - OpenAPI 使用“oneof”属性从 swagger 生成 spring
- sql - 如何汇总 BigQuery 中排除窗口的列中的所有值,然后将结果设置到此排除窗口中?
- r - 如何迭代rep()中的变量
- python - .pop() 不会为双端队列对象执行
- jquery - 根据 CORS 预检响应 ajax django 中的标头“Access-Control-Allow-Headers”,标头“access-control-allow-credentials”是不允许的
- java - android 6.0以后可以去掉wifi网络吗?
- html - HTML 标题和表格分为 2 页
- android - 如何使用 MockK 测试挂起功能?
- jsonb - 搜索和提取位于 json 结构的各种路径中的元素
- ios - 在 iOS 13 中可以在没有 UIActivityViewController 的情况下将内容分享到特定的社交网络并打开直接需要的扩展程序吗?