six.text_type与text.decode('utf8')相同吗?

问题描述 投票:0回答:1

给出类似的功能:

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无法捕获的情况?
python text unicode six
1个回答
0
投票
由于six.text_type仅是对strunicode类型的引用,所以等效功能为:

def convert_to_unicode(text): return six.text_type(text, encoding='utf8', errors='ignore')

但是,在极端情况下,例如,它只会愉快地转换一个整数,因此您必须首先在此处进行一些检查。

而且,我不明白您为什么要拥有errors='ignore'。您说您假设使用UTF-8。但是,如果违反了此假设,则您将静默删除数据。我强烈建议使用errors='strict'

© www.soinside.com 2019 - 2024. All rights reserved.