【问题标题】:Matplotlib objects nodes, unicode __str___Matplotlib 对象节点,unicode __str___
【发布时间】:2013-09-08 11:10:12
【问题描述】:

我对所有这些 un​​icode 问题感到非常厌倦。我需要用对象节点构建图。我需要展示这张图。我有可视化 unicode 字符串的问题。 所以... 要将对象作为图形节点,我需要重写 equal 和 hash 方法

class VkUser:
    def __init__(self,uid=None,f_name = None,l_name = None,json=None):
        if(json==None):
            self.uid=uid
            self.l_name=l_name
            self.f_name=f_name
        else:
            self.uid = json['uid']
            self.f_name = json['first_name']
            self.l_name = json['last_name']
    def __eq__(self, other):
        if isinstance(other, VkUser):
            return (self.uid == other.uid)
        return NotImplemented
    def __ne__(self, other):
        result = self.__eq__(other)
        if result is NotImplemented:
            return result
        return not result
    def __hash__(self):
        return hash(self.uid)

但是,如果我不想将指针作为图形的节点,我需要覆盖 str

def __str__(self):
        return '%s %s'%(self.f_name,self.l_name)

它工作正常,而我只有英文字母。

但我有带有 unicode 俄语字母的 Json 输入,我需要在图表上显示它们。 有点像

Me = VkUser(111,u'\u0410\u043b\u0435\u043a\u0441\u0430\u043d\u0434\u0440',u'\u0410\u043b\u0435\u043a\u0441\u0430\u043d\u0434\u0440')

现在我遇到了错误

   label=str(label) # this will cause "1" and 1 to be labeled the same
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-8: ordinal not in range(128)

我在 str

中尝试了不同的变体

def str(自我): return u'%s %s'%(self.f_name,self.l_name) 同样的错误

def __str__(self):
        res = u'%s %s'%(self.f_name,self.l_name)
        return res.encode('utf-8')
...
ValueError: matplotlib display text must have all code points < 128 or use Unicode strings

请帮帮我,我受够了。

【问题讨论】:

  • 你用的是什么版本的mpl和python?尝试摆脱 str,这就是试图将其转换回 ascii 的原因。你能把你的代码整合成一个最小的例子吗? sscce.org

标签: python unicode matplotlib tostring object-to-string


【解决方案1】:
l = u'\u0410\u043b\u0435\u043a\u0441\u0430\u043d\u0434\u0440'
plot(range(5), label=l)
legend()

使用 2.7 和几乎最新的母版 (1.4.x) 时的行为符合我的预期(好吧,我没有这些字符的字体,所以我得到了框)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多