Python 对其文本编解码器非常挑剔。不幸的是,任何事情都可能并且将会在文本中发生,外来词和行噪音是主要的例子。发生这种情况时,我不能让我的生产系统显示错误并停止。什么是好的故障保护方法?有没有我可以使用的方法或库,例如,简单地忽略编解码器无法识别的任何内容?
问问题
51 次
2 回答
2
您可以指定codecs.openerrors
的参数。它默认为which throws 异常,但和是一些其他选项。'strict'
'ignore'
'replace'
于 2015-03-05T17:57:13.407 回答
0
您可以使用try
和except
:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
s='eëeéeę'
try:
a=s.decode('ascii')
except UnicodeDecodeError:
# handle the error appropriately...
# this is just an example:
a='cant decode "s"'
于 2015-03-05T17:53:25.790 回答