【问题标题】:Change Unicode to Str returns "not supported"将 Unicode 更改为 Str 返回“不支持”
【发布时间】:2019-03-27 06:06:11
【问题描述】:

在程序代码中返回的是“unicode is not defined”。从 unicode 到 str 的更改返回“不支持 str”。有什么问题或遗漏?

for header in [ 'subject' ]:
    dh = email.header.decode_header(msg[header])
    default_charset = 'ASCII'
    print('%-8s: %s' % (header.upper(), ''.join([ unicode(t[0], t[1] or default_charset) for t in dh ])))

【问题讨论】:

    标签: python python-3.x email character-encoding decode


    【解决方案1】:

    unicode 内置函数在 Python 3 中不存在 - 这就是为什么您会收到异常 NameError: name 'unicode' is not defined。在 Python 3 中,unicode 的等价物是 str

    unicode 一样,str 接受一个编码参数,并将尝试使用提供的编码解码一个字节串。如果您将str 实例传递给str 进行解码,您将得到TypeError: decoding str is not supported

    email.header.decode_header 的输出可能同时包含 strbytes 实例,因此您的理解需要能够同时处理这两个实例:

    print('%-8s: %s' % ('subject'.upper(), ''.join(t[0] if isinstance(t[0], str) else str(t[0], t[1] or default_charset) for t in dh)))
    

    (在 Python 3 中,最好将 default_charset 设置为 'utf-8')。

    最后,如果您控制消息对象的创建方式,则可以通过在创建消息时指定策略对象来自动解码标头(Python 3.5+)。

    >>> from email.policy import default
    >>> with open('message.eml', 'rb') as f:
    ...     msg = email.message_from_bytes(f.read(), policy=default)
    >>>
    
    >>> for x in msg.raw_items():print(x)
    ... 
    ('Subject', 'Ayons asperges pour le =?utf-8?q?d=C3=A9jeuner?=')
    ('From', '=?utf-8?q?Pep=C3=A9?= Le Pew <pepe@example.com>')
    ('To', 'Penelope Pussycat <penelope@example.com>,\n Fabrette Pussycat <fabrette@example.com>')
    ('Content-Type', 'text/plain; charset="utf-8"')
    ('Content-Transfer-Encoding', 'quoted-printable')
    ('MIME-Version', '1.0')
    >>> msg['from']
    'Pepé Le Pew <pepe@example.com>'
    >>> msg['subject']
    'Ayons asperges pour le déjeuner'
    

    (消息数据取自电子邮件examples)。

    【讨论】:

      猜你喜欢
      • 2019-07-24
      • 2018-03-29
      • 2017-07-23
      • 2020-02-03
      • 1970-01-01
      • 2013-05-14
      • 2011-04-15
      • 2013-08-08
      • 2017-06-29
      相关资源
      最近更新 更多