7

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

mystring="=AC=E9"

该字符串应打印为

é

所以我想解码它并用 UTF-8 编码它。我明白有些事情是可能的

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

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

4

3 回答 3

9
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 编码的字节对象(这可能是您想要的)。如果要打印字符“é”,请使用 .decode() 解码utf-8编码字节对象并将“utf-8”作为参数传递。

于 2018-09-07T05:21:18.017 回答
5

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

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
于 2017-05-07T15:20:22.583 回答
1

尝试这个。

import quopri
mystring="=AC=E9"
decoded_string=quopri.decodestring(mystring)
print(decoded_string.decode('windows-1251'))
于 2017-05-06T20:17:10.827 回答