代码之家  ›  专栏  ›  技术社区  ›  Programer Beginner

Python 2在一个句子中以矩形打印emoji

  •  0
  • Programer Beginner  · 技术社区  · 7 年前

    我有这个( 拍手 表情符号) string.txt 文件(编码为 utf-8 ).

    我试图用一个句子将它打印到默认的python IDLE中。

    with open('string.txt','r') as f:
        string = f.read()
    

    代码:

    >>> string
    '\xf0\x9f\x98\xad\xf0\x9f\x91\x8f\xf0\x9f\x8f\xbb'
    
    >>> print string
    ð゚リᆳð゚ムマð゚マᄏ
    
    >>> print string.decode('utf-8')
    😭👏🏻    # <-- this is the output I want in a middle of sentence
    

    这是我想要的输出(矩形)。棘手的是,我希望他们在句子中间。所以:

    >>> print 'The string is: {}!'.format(string.decode('utf-8')) # will get error
    Traceback (most recent call last):
      File "<pyshell#81>", line 1, in <module>
        print 'The string is: {}!'.format(string.decode('utf-8'))
    UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)
    

    有个错误。但如果我不破译它,它会起作用:

    >>> print 'The string is: {}!'.format(string)
    The string is: ð゚リᆳð゚ムマð゚マᄏ!
    

    它没有引发任何错误,但我不希望此输出。我要长方形。

    >>> print 'The string is: {}!'.format(magical_string)
    The string is: 😭👏🏻!
    

    最好不要使用任何第三方库。

    编辑:

    我的操作系统: (适用于所有Windows 7-10的首选解决方案)

    蟒蛇:

    1 回复  |  直到 7 年前
        1
  •  1
  •   Joost    7 年前

    我认为这是IDE的一个设置,而不是真正的python问题。

    当我将问题的第一行保存到txt文件中并读取时:

    >>> open('test.txt').read()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\Users\joost\Desktop\pythontests\venv\lib\encodings\cp1252.py", line 23, in decode
        return codecs.charmap_decode(input,self.errors,decoding_table)[0]
    UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 19: character maps to <undefined>
    >>> open('test.txt', encoding='utf-8').read()
    'I have this 😭👏🏻 (loudly crying\n'
    >>>
    

    如图所示:

    enter image description here

    也许在打开文件时指定编码?