在Python中,我得到了一个用Quoted-Printable encoding编码的字符串
mystring="=AC=E9"
该字符串应打印为
é
所以我想解码它并用UTF-8编码,我想。我知道有可能通过
import quopri
quopri.decodestring('=A3=E9')
但后来,我完全迷失了。您将如何解码/编码此字符串以正确打印?
import quopri
编码方式:
您可以使用quopri.encodestring()将字符'é'编码为Quoted-Printable。它需要一个bytes对象并返回QP编码的bytes对象。
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编码的字节对象(可能是你想要的)。如果要打印字符'é',请使用.decode()解码utf-8编码的字节对象,并将'utf-8'作为参数传递。
好的,我不知道究竟为什么,但这个功能似乎工作:
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
试试这个。
import quopri
mystring="=AC=E9"
decoded_string=quopri.decodestring(mystring)
print(decoded_string.decode('windows-1251'))