问题描述
爬虫时遇到不可见字符时无法导入数据库中,报错 mysql.connector.errors.DatabaseError: 1267 (HY000): Illegal mix of collations (gbk_chinese_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='
遇到的不可见字符有:
\u200b
\ufeff
\ue601
还有其他不可见字符,可用 repr(s)
显示其原本的样子
s = chr(8204) + chr(8205)
print(s)
print(repr(s)) # '\u200c\u200d'
解决方案
利用 str.isprintable()
,如果字符串中所有字符均为可打印字符或空字符串则返回 True
,否则返回 False
print(''.isprintable()) # True
print('A'.isprintable()) # True
print('A\u2029'.isprintable()) # False
移除所有不可见字符
def remove_upprintable_chars(s):
"""移除所有不可见字符"""
return ''.join(x for x in s if x.isprintable())
s = 'A\u2029B'
print(s.isprintable(), s) # False
s = remove_upprintable_chars(s)
print(s.isprintable(), s) # True
其他
备选方案如下:
- 将字符集改为
utf8
- 读取编码改为
utf-8-sig
- 直接替换掉
s = s.replace('\u200b', '')
另外,参考文献通过该方法去除控制字符,本人测试无效
import re
import itertools
def remove_control_chars(s):
control_chars = ''.join(map(chr, itertools.chain(range(0x00, 0x20), range(0x7f, 0xa0))))
control_char_re = re.compile('[%s]' % re.escape(control_chars))
return control_char_re.sub('', s)