如何在 python 中将原始 unicode 转换为 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 可读格式,然后才能继续我的工作。
基本上我需要能够做到这一点:
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)解决。非常感谢。 post.
下的两种解决方案
已解决:
我发现了模块 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
第一次来,我会尽力解释我的问题。
我正在 Maya 中使用 python2.7。 我得到了一个字符串(称为属性)'attr',它是用 Maya 的 API 导入的,如下所示:
print(attr)
print(type(attr))
>> Générique
>> <type 'unicode'>
我需要先将其转换为 utf-8 可读格式,然后才能继续我的工作。 基本上我需要能够做到这一点:
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)解决。非常感谢。 post.
下的两种解决方案已解决:
我发现了模块 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