【问题标题】:Encoding issue : decode Quoted-Printable string in Python编码问题:在 Python 中解码 Quoted-Printable 字符串
【发布时间】:2017-10-05 02:22:03
【问题描述】:

在 Python 中,我得到了一个用 Quoted-Printable encoding 编码的字符串

mystring="=AC=E9"

这个字符串应该打印为

é

所以我想对它进行解码并用 UTF-8 编码。我知道有些事情可以通过

import quopri
quopri.decodestring('=A3=E9')

但是,我完全迷路了。您将如何解码/编码此字符串以正确打印?

【问题讨论】:

    标签: python encoding decoding quoted-printable


    【解决方案1】:
    import quopri
    

    编码:

    您可以使用 quopri.encodestring() 将字符“é”编码为 Quoted-Printable。它接受一个字节对象并返回 QP 编码的字节对象。

    encoded = quopri.encodestring('é'.encode('utf-8'))
    print(encoded)
    

    打印 b'=C3=A9'(但不是问题中指定的“=AC=E9”或“=A3=E9”)

    解码:

    mystring = '=C3=A9'
    decoded_string = quopri.decodestring(mystring)
    print(decoded_string.decode('utf-8'))
    

    quopri.decodestring() 返回一个以 utf-8 编码的 bytes 对象(这可能是您想要的)。如果您想打印字符 'é',请使用 .decode() 解码 utf-8 编码字节对象,并将 'utf-8' 作为参数传递。

    【讨论】:

      【解决方案2】:

      好吧,伙计们,我不知道为什么,但这个功能似乎有效:

      from email.parser import Parser
      
      def decode_email(msg_str):
          p = Parser()
          message = p.parsestr(msg_str)
          decoded_message = ''
          for part in message.walk():
              charset = part.get_content_charset()
              if part.get_content_type() == 'text/plain':
                  part_str = part.get_payload(decode=1)
                  decoded_message += part_str.decode(charset)
          return decoded_message
      

      【讨论】:

        【解决方案3】:

        试试这个。

        import quopri
        mystring="=AC=E9"
        decoded_string=quopri.decodestring(mystring)
        print(decoded_string.decode('windows-1251'))
        

        【讨论】:

        • 不幸的是,我之前尝试过,但看起来 windows-1251 是为编码俄语而设计的。当我运行你的代码块时,我得到一个打印的 ¬й 。这不是它应该看起来的样子。一个'é'
        猜你喜欢
        • 2012-03-05
        • 2014-03-01
        • 1970-01-01
        • 2019-04-29
        • 2018-02-01
        • 2011-01-14
        • 2011-09-24
        • 2011-05-01
        相关资源
        最近更新 更多