Python去除不可见字符,如\u200b

问题描述

爬虫时遇到不可见字符时无法导入数据库中,报错 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)




参考文献

  1. python - SimpleJSON encoding issue: Illegal character
  2. python 去除不可见的控制字符
  3. Stripping non printable characters from a string in python
  4. unicodedata — Unicode 数据库
  5. Python批量替换字符串内容
  6. mysql字符集错误ERROR 1267 (HY000)解决方法
  7. 去除 \ufeff
  8. 如何移除所有不可见字符?
  9. str.isprintable() — Python文档
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XerCis

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值