【问题标题】:How to make Python Interactive Shell print cyrillic symbols?如何让 Python Interactive Shell 打印西里尔符号?
【发布时间】:2015-05-26 09:31:50
【问题描述】:

我在我的项目中使用 Pymorphy2 作为西里尔语形态分析器。 但是当我尝试打印出单词列表时,我得到了这个:

>>> for t in terms:
...     p = morph.parse(t)
...     if 'VERB' in p[0].tag:
...             t = p[0].normal_form
...     elif 'NOUN' in p[0].tag:
...             t = p[0].lexeme[0][0]
... 
>>> terms
[u'\u041f\u0430\u0432\u0435\u043b', u'\u0445\u043e\u0434\u0438\u0442', u'\u0434\u043e\u043c\u043e\u0439']

如何在 python shell 中打印俄语字符?

【问题讨论】:

    标签: python shell unicode character-encoding cyrillic


    【解决方案1】:

    您将看到 unicode 字符串的 repr 表示,如果您遍历列表或索引并打印每个字符串,您将看到所需的输出。

    In [4]: terms
    Out[4]: 
    [u'\u041f\u0430\u0432\u0435\u043b',
     u'\u0445\u043e\u0434\u0438\u0442',
     u'\u0434\u043e\u043c\u043e\u0439'] # repr
    
    In [5]: print terms[0] # str 
    Павел
    
    In [6]: print terms[1]
    ходит
    

    如果您希望它们全部打印出来并看起来像一个列表,请使用 str.format 和 str.join:

    terms = [u'\u041f\u0430\u0432\u0435\u043b',
     u'\u0445\u043e\u0434\u0438\u0442',
     u'\u0434\u043e\u043c\u043e\u0439']
    
    print(u"[{}]".format(",".join(terms)))
    

    输出:

    [Павел,ходит,домой]
    

    【讨论】:

    • 但是,如果我在列表中有 1000 个元素,并且希望看到打印出来的整个单词列表而不需要对列表进行冗余迭代怎么办?
    • 当你打印列表时,它无论如何都会被迭代。如果你需要经常打印这样的列表——你可以实现print_list函数
    • @paus:想想print(unicode_text)print(repr(unicode_text))(或Python 3 上的print(ascii(unicode_text)))之间的区别。要打印整个列表:for t in terms: print(t)print("\n".join(terms))。如果不对其进行迭代,您将无法打印列表。
    猜你喜欢
    • 2014-07-17
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 2017-10-05
    • 2011-10-19
    • 1970-01-01
    • 2016-05-10
    相关资源
    最近更新 更多