python - 将 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 ])))
解决方案
Python 3 中不存在unicode内置函数 -这就是您得到异常的原因NameError: name 'unicode' is not defined
。unicode
在 Python 3中,相当于str。
Like unicode
,str
接受一个编码参数,并尝试使用提供的编码解码一个字节串。如果您将str
实例传递给str
进行解码,您将获得TypeError: decoding str is not supported
.
email.header.decode_header的输出可以同时包含str
和bytes
实例,因此您的理解需要能够同时处理这两者:
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'
(从电子邮件示例中获取的消息数据)。
推荐阅读
- spring - How can i make my Spring Batch job to restart from a specific value in the database column?
- google-cloud-platform - GCP Data Loss Prevention API How to deindentify free text column in table
- java - Java/selenium : list.clear(); clearing the result that i was trying to store in map before clearing the list
- python - python nutrition log. Assigning multiple values to each key
- aws-cdk - AWS CDK - .Net Core Build Task
- python - why python delete object cost a long time?
- kotlin - Kotlin 的范围检查是否有效?
- sql - How to make a foreign key in reference to a column of the same table
- c# - 如何将嵌套数组从 C# 编组到 C++?
- formatjs - Error using multi-word matches with {key, select, matches}