给出类似的功能:
import six
def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("utf-8", "ignore")
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
elif six.PY2:
if isinstance(text, str):
return text.decode("utf-8", "ignore")
elif isinstance(text, unicode):
return text
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
else:
raise ValueError("Not running on Python2 or Python 3?")
由于six
处理了python2和python3的兼容性,所以[[上述convert_to_unicode(text)
函数是否仅等同于six.text_type(text)
?,即
def convert_to_unicode(text):
return six.text_type(text)
是否有原始convert_to_unicode
捕获但six.text_type
无法捕获的情况?
six.text_type
仅是对str
或unicode
类型的引用,所以等效功能为:def convert_to_unicode(text):
return six.text_type(text, encoding='utf8', errors='ignore')
但是,在极端情况下,例如,它只会愉快地转换一个整数,因此您必须首先在此处进行一些检查。而且,我不明白您为什么要拥有
errors='ignore'
。您说您假设使用UTF-8。但是,如果违反了此假设,则您将静默删除数据。我强烈建议使用errors='strict'
。