亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Six.text_type 和 text.decode('utf8') 一樣嗎?

Six.text_type 和 text.decode('utf8') 一樣嗎?

牛魔王的故事 2022-06-14 15:29:57
給定一個函數,如:import sixdef 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)函數是否等同于 just six.text_type(text)?IEdef convert_to_unicode(text):    return six.text_type(text)是否存在原始convert_to_unicode捕獲但six.text_type不能捕獲的情況?
查看完整描述

1 回答

?
慕的地6264312

TA貢獻1817條經驗 獲得超6個贊

由于six.text_typeist 只是對strorunicode類型的引用,因此等效函數將是:


def convert_to_unicode(text):

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

但它在極端情況下的行為并不相同,例如。它會很高興地轉換一個整數,所以你必須先在那里做一些檢查。


另外,我不明白您為什么要擁有errors='ignore'. 你說你假設 UTF-8。但是,如果違反此假設,您將默默地刪除數據。我強烈建議使用errors='strict'.


編輯:

text我剛剛意識到,如果已經是您想要的,這將不起作用。此外,它很高興為任何非字符串輸入引發 TypeError。那么這個怎么樣:


def convert_to_unicode(text):

    if isinstance(text, six.text_type):

        return text

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

這里發現的唯一極端情況是 Python 版本既不是 2 也不是 3。我仍然認為你應該使用errors='strict'.


查看完整回答
反對 回復 2022-06-14
  • 1 回答
  • 0 關注
  • 312 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號