编码问题:如何在Python中解码Quoted-Printable字符串

11

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

mystring="=AC=E9"

这个字符串应该打印为

é

所以我想要解码并使用UTF-8重新编码它。我猜这是可能的。我知道可以通过

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

但是,接下来我完全不知道该怎么做。您如何对此字符串进行解码/编码以正确打印?
3个回答

13
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() 返回一个字节(bytes)对象, 该对象使用utf-8进行编码(这可能是您想要的)。如果您希望打印字符'é',请使用.decode()解码utf-8编码的字节对象并将'utf-8'作为参数传递。


7

大家好,我不确定为什么,但是这个函数似乎有效:

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

1
尝试这个。
import quopri
mystring="=AC=E9"
decoded_string=quopri.decodestring(mystring)
print(decoded_string.decode('windows-1251'))

不幸的是,我以前尝试过这个,但它看起来 windows-1251 是设计用来编码俄语的。当我运行你的代码块时,我得到了一个打印出来的 ¬й。这不是它应该看起来的样子。应该是一个 'é'。 - hans glick

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接