我正在将数千万行文本数据从 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%';
+--------------------------------------+-----------------+
|变量名 |值(value)|
+--------------------------------------+-----------------+
|字符集客户端 | utf8 |
|字符集连接 | utf8 |
|字符集数据库 | utf8 |
|字符集文件系统 |二进制 |
|字符集结果 | utf8 |
|字符集服务器 | utf8 |
|字符集系统 | utf8 |
|排序规则连接 | utf8_general_ci |
|排序规则数据库 | 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)
最佳答案
它提示十六进制ED
。您是否期待acute-i: í
?如果是这样,那么您拥有的文本不是编码的 UTF-8,而是 cp1250、dec8、latin1、latin2、latin5 之一。
你的Python源代码是否以以下开头
# -*- coding: utf-8 -*-
另外,请查看“最佳实践”here
您有charset='utf-8'
;我不确定,但也许应该是 charset='utf8'
。 Reference UTF-8
是世人所说的字符集。 MySQL 将其 3 字节子集称为 utf8
。请注意没有破折号。
关于mysql - 如何捕获由于 mysql 数据中无效的连续字节而导致的 UnicodeDecodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51347997/