如何在python2中做surrogateescape

lxy*_*xyu 8 python unicode python-2.x surrogate-pairs

Python3改变了unicode行为以拒绝代理对,而python2则没有.

有一个问题在这里

但它没有提供如何在python2中删除代理对或如何进行代理转义的解决方案.

Python3示例:

>>> a = b'\xed\xa0\xbd\xe4\xbd\xa0\xe5\xa5\xbd'
>>> a.decode('utf-8', 'surrogateescape')
'\udced\udca0\udcbd??'
>>> a.decode('utf-8', 'ignore')
'??'
Run Code Online (Sandbox Code Playgroud)

'\ xed\xa0\xbd'这里不是正确的utf-8字符.我想忽略它们或逃脱它们.

是否有可能在python2中做同样的事情?

pro*_*ski 5

没有内置的解决方案,但在python-future中有一个surrogateescapes的实现:https: //github.com/PythonCharmers/python-future

添加from future.utils.surrogateescape import register_surrogateescape到导入.然后调用该方法register_surrogateescape(),然后您可以errors='surrogateescape'encode和中使用错误处理程序decode.

这里可以找到一个例子