首页 > 解决方案 > 将 Unicode 更改为 Str 返回“不支持”

问题描述

在程序代码中返回的是“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 ])))

标签: pythonpython-3.xemailcharacter-encodingdecode

解决方案


Python 3 中不存在unicode内置函数 -这就是您得到异常的原因NameError: name 'unicode' is not definedunicode在 Python 3中,相当于str

Like unicodestr接受一个编码参数,并尝试使用提供的编码解码一个字节串。如果您将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'

(从电子邮件示例中获取的消息数据)。


推荐阅读