Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以将decode(errors=“ignore”作为Python 2.7程序中所有字符串的默认值吗?_Python_Python 2.7_Decode - Fatal编程技术网

我可以将decode(errors=“ignore”作为Python 2.7程序中所有字符串的默认值吗?

我可以将decode(errors=“ignore”作为Python 2.7程序中所有字符串的默认值吗?,python,python-2.7,decode,Python,Python 2.7,Decode,我有一个Python 2.7程序,可以从各种外部应用程序中写出数据。当我写入文件时,我不断地被异常所困扰,直到我将.decode(errors=“ignore”)添加到正在写入的字符串中。(FWIW,以mode=“wb”打开文件并不能解决此问题。) 有没有办法说“忽略此范围内所有字符串上的编码错误”您不能在内置类型上重新定义方法,也不能将errors参数的默认值更改为str.decode()。不过,还有其他方法可以实现所需的行为 稍微好一点的方法:定义自己的decode()函数: def dec

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


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

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

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

def decode(s, encoding="ascii", errors="ignore"):
    return s.decode(encoding=encoding, errors=errors)
import codecs
codecs.register_error("strict", codecs.ignore_errors)
现在,您需要调用
decode(s)
,而不是
s.decode()
,但这也不太糟糕,不是吗

hack:您不能更改
errors
参数的默认值,但您可以覆盖默认
errors=“strict”
的处理程序所做的操作:

import codecs
def strict_handler(exception):
    return u"", exception.end
codecs.register_error("strict", strict_handler)
这将从本质上将
errors=“strict”
的行为更改为标准的
“ignore”
行为。请注意,这将是一个全局更改,影响您导入的所有模块


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

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

class easystr(str):
    def decode(self):
        return str.decode(self, errors="ignore")
如果随后将所有传入字符串转换为
easystr
,错误将被忽略:

line = easystr(input.readline())
也就是说,对字符串进行解码会将其转换为unicode,而unicode永远不会丢失。您能否找出字符串使用的是哪种编码,并将其作为
解码
参数?这将是一个更好的解决方案(您仍然可以通过上述方式将其设置为默认设置)

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

import codecs
input = codecs.open(filename, "r", encoding="latin-1") # or whatever
甚至在没有新功能的情况下,也可以进行黑客攻击:

def decode(s, encoding="ascii", errors="ignore"):
    return s.decode(encoding=encoding, errors=errors)
import codecs
codecs.register_error("strict", codecs.ignore_errors)