【问题标题】:Can I make decode(errors="ignore") the default for all strings in a Python 2.7 program?我可以将 decode(errors="ignore") 设为 Python 2.7 程序中所有字符串的默认值吗?
【发布时间】:2012-03-21 04:42:03
【问题描述】:

我有一个 Python 2.7 程序,可以从各种外部应用程序中写出数据。当我写入文件时,我不断地被异常所困扰,直到我将.decode(errors="ignore") 添加到正在写出的字符串中。 (FWIW,以mode="wb" 打开文件并不能解决此问题。)

有没有办法说“忽略此范围内所有字符串的编码错误”?

【问题讨论】:

  • 您的问题得到解答了吗?

标签: python python-2.7 decode


【解决方案1】:

As mentioned in my thread on the issue 来自 Sven Marnach 的 hack 甚至可以在没有新功能的情况下实现:

import codecs
codecs.register_error("strict", codecs.ignore_errors)

【讨论】:

    【解决方案2】:

    我不确定你的设置到底是什么,但你可以从str 派生一个类并覆盖它的解码方法:

    class easystr(str):
        def decode(self):
            return str.decode(self, errors="ignore")
    

    如果您随后将所有传入的字符串转换为easystr,错误将被静默忽略:

    line = easystr(input.readline())
    

    也就是说,解码一个字符串会将其转换为 unicode,这绝不应该是有损的。你能弄清楚你的字符串使用的是哪种编码,并将其作为encoding 参数提供给decode 吗?那将是一个更好的解决方案(您仍然可以通过上述方式将其设为默认值)。

    您应该尝试的另一件事是读取不同的数据。这样做,解码错误可能会消失:

    import codecs
    input = codecs.open(filename, "r", encoding="latin-1") # or whatever
    

    【讨论】:

      【解决方案3】:

      您不能重新定义内置类型的方法,也不能将errors 参数的默认值更改为str.decode()。不过,还有其他方法可以实现所需的行为。

      稍微好一点的方法:定义你自己的decode()函数:

      def decode(s, encoding="ascii", errors="ignore"):
          return s.decode(encoding=encoding, errors=errors)
      

      现在,您需要调用 decode(s) 而不是 s.decode(),但这还不错,不是吗?

      技巧:您无法更改errors 参数的默认值,但您可以覆盖默认errors="strict" 的处理程序所做的事情:

      import codecs
      def strict_handler(exception):
          return u"", exception.end
      codecs.register_error("strict", strict_handler)
      

      这将从本质上将errors="strict" 的行为更改为标准的"ignore" 行为。请注意,这将是一个全局更改,会影响您导入的所有模块。

      我不推荐这两种方式。真正的解决方案是正确编码。 (我很清楚这并不总是可能的。)

      【讨论】:

        猜你喜欢
        • 2019-07-27
        • 1970-01-01
        • 1970-01-01
        • 2020-02-21
        • 1970-01-01
        • 2011-04-05
        • 2012-08-13
        • 2016-09-19
        • 2011-10-24
        相关资源
        最近更新 更多