簡體   English   中英

如何將原始 unicode 轉換為 python 中的 utf8-unicode?

[英]How to convert raw unicode to utf8-unicode in python?

第一次來這里,我會盡力解釋我的問題。

我在 Maya 中使用 python2.7。 我得到了一個字符串(稱為屬性)'attr',它是用 Maya 的 API 導入的,如下所示:

print(attr)
print(type(attr))

>> Générique
>> <type 'unicode'>

我需要將其轉換為 utf-8 可讀格式,然后才能 go 繼續我的工作。 基本上我需要能夠做到這一點:

print(attr)
print(type(attr))

>>Générique
>><type 'unicode'>

我嘗試了 attr.encode / attr.decode 的多種組合,但我無法真正掌握我應該做什么。 最讓我困擾的是,當我嘗試在代碼中手動鍵入變量時,您實際上可以得到:

attr = 'Générique'
print(type(attr))
attr = attr.decode('utf-8')
print(attr)
print(type(attr))

>><type 'str'>
>>Générique
>><type 'unicode'>

所以我知道我應該首先將 'attr' 轉換為 str 類型,但我不能在不丟失其中信息的情況下做到這一點。

有任何想法嗎? 請?

編輯:由 snakecharmerb(和 ftfy)解決。 非常感謝。 這篇文章下的兩種解決方案。

解決了:

我發現了模塊 FTFY。 讓 pip 與 Maya 一起工作有點麻煩,但一切都很好,完成了。 對於有相同問題的任何人:使 pip 與 maya 一起工作: https://forums.autodesk.com/t5/maya-programming/can-i-use-pip-in-maya-script-editor/td-p/7638107 (你需要運行 admin cmd 否則它不會安裝)

grab ftfy(5以下版本兼容python2.7):pip install ftfy==4.4.3

我不干凈的代碼是這樣的:

from __future__ import unicode_literals
import pymel.core as pm
import maya.cmds as cmds
import maya.utils
import unicodedata
import StringIO
import codecs
import sys
import re
from ftfy import fix_text

attr = cmds.getAttr(*objectName*)
attr = fix_text(attr)
print(attr)

您所擁有的是最初為 UTF-8 但使用 8 位編碼(可能是 latin-1 或 cp1252)解碼的文本。 要修復文本,您需要編碼為 8 位編碼以獲取 UTF-8 字節,然后進行解碼。

>>> u = u'Générique'
>>> fixed = u.encode('latin-1').decode('utf-8')
>>> print fixed
Générique

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM