【问题标题】:How to convert raw unicode to utf8-unicode in python?如何在 python 中将原始 unicode 转换为 utf8-unicode?
【发布时间】:2020-07-28 14:06:08
【问题描述】:

第一次来这里,我会尽力解释我的问题。

我在 Maya 中使用 python2.7。 我得到了一个使用 Maya 的 API 导入的字符串(称为属性)“attr”,如下所示:

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)解决。非常感谢。这篇文章下的两种解决方案。

【问题讨论】:

    标签: python python-2.7 character-encoding


    【解决方案1】:

    您所拥有的是最初是 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
    

    【讨论】:

      【解决方案2】:

      已解决:

      我发现了 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)
      

      【讨论】:

        猜你喜欢
        • 2017-02-24
        • 1970-01-01
        • 1970-01-01
        • 2013-06-14
        • 2021-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多