Last active
January 1, 2016 23:09
-
-
Save huyx/8214895 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import functools | |
def unicode2str(o, encoding='utf-8', errors='strict'): | |
'''把对象中的 unicode 字符串编码成 str | |
:param o: 要解码的对象 | |
:param encoding: 编码类型 | |
:param errors: strict|ignore|replace 参见 ''.encode 中的说明 | |
>>> deep_encode(([u'a'], {u'b': u'c'})) | |
(['a'], {'b': 'c'}) | |
''' | |
_ = functools.partial(deep_encode, encoding=encoding, errors=errors) | |
if isinstance(o, unicode): | |
return o.encode(encoding, errors) | |
if isinstance(o, dict): | |
return {_(k): _(v) for k, v in o.iteritems()} | |
if isinstance(o, list): | |
return map(_, o) | |
if isinstance(o, tuple): | |
return tuple(map(_, o)) | |
return o | |
def str2unicode(o, encoding='utf-8', errors='strict'): | |
'''把对象中的 str 字符串编码成 unicode | |
:param o: 要解码的对象 | |
:param encoding: 编码类型 | |
:param errors: strict|ignore|replace 参见 ''.decode 中的说明 | |
>>> deep_decode((['a'], {'b': 'c'})) | |
([u'a'], {u'b': u'c'}) | |
''' | |
_ = functools.partial(deep_decode, encoding=encoding, errors=errors) | |
if isinstance(o, str): | |
return o.decode(encoding, errors) | |
if isinstance(o, dict): | |
return {_(k): _(v) for k, v in o.iteritems()} | |
if isinstance(o, list): | |
return map(_, o) | |
if isinstance(o, tuple): | |
return tuple(map(_, o)) | |
return o | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment