gpt4 book ai didi

Python 统一码 : how to replace character that cannot be decoded using utf8 with whitespace?

转载 作者:太空狗 更新时间:2023-10-30 00:49:12 24 4
gpt4 key购买 nike

如何用空格替换utf8无法解码的字符?

# -*- coding: utf-8 -*-
print unicode('\x97', errors='ignore') # print out nothing
print unicode('ABC\x97abc', errors='ignore') # print out ABCabc

如何打印出 ABC abc 而不是 ABCabc?请注意,\x97 只是一个示例字符。无法解码的字符是未知输入。

  • 如果我们使用errors='ignore',它什么也不会打印出来。
  • 如果我们使用 errors='replace',它将用一些特殊字符替换该字符。

最佳答案

看看 codecs.register_error。您可以使用它来注册自定义错误处理程序

https://docs.python.org/2/library/codecs.html#codecs.register_error

import codecs
codecs.register_error('replace_with_space', lambda e: (u' ',e.start + 1))
print unicode('ABC\x97abc', encoding='utf-8', errors='replace_with_space')

关于Python 统一码 : how to replace character that cannot be decoded using utf8 with whitespace?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32115830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com