【问题标题】:Python unicode: how to replace character that cannot be decoded using utf8 with whitespace?Python unicode:如何用空格替换无法使用utf8解码的字符?
【发布时间】:2015-08-20 10:31:06
【问题描述】:

如何用空格替换无法使用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',它将用一些特殊字符替换那个字符。

【问题讨论】:

    标签: python unicode utf-8


    【解决方案1】:

    看看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')
    

    【讨论】:

    • 堆栈溢出是否允许多个解决方案? @Kasramvd 和你都提供了很好的答案......在这种情况下该怎么办......
    【解决方案2】:

    您可以使用try-except 语句来处理UnicodeDecodeError

    def my_encoder(my_string):
       for i in my_string:
          try :
             yield unicode(i)
          except UnicodeDecodeError:
             yield '\t' #or another whietespaces 
    

    然后使用str.join 方法加入你的字符串:

    print ''.join(my_encoder(my_string))
    

    演示:

    >>> print ''.join(my_encoder('this is a\x97n exam\x97ple'))
    this is a   n exam  ple
    

    【讨论】:

    • \x97 只是一个示例字符。无法解码的字符是未知输入。
    • @DehengYe 只是一个错字,已修复
    • 非常有帮助的答案! @Kasramvd
    • 希望你不要介意。你和@HelloWorld 都提供了很好的答案。但是 Stack Overflow 只允许一种解决方案。
    猜你喜欢
    • 1970-01-01
    • 2017-10-15
    • 2013-05-01
    • 2023-01-09
    • 2019-10-29
    • 2021-05-11
    • 1970-01-01
    • 2017-12-09
    • 2021-03-11
    相关资源
    最近更新 更多