Python编码从ISO到UTF8
我正在用一个Python脚本(Python 2.5和PyPy)读取我的电子邮件。结果中有些内容不是ASCII格式,所以我得到了这样的字符串:
=?ISO-8859-7?B?0OXm7/Dv8d/hIPP07+0gyuno4enx/u3h?='
有没有办法把它解码并转换成utf-8格式,这样我就可以处理它了?我试过用.decode('ISO-8859-7'),但得到的还是同样的字符串。
2 个回答
5
import email.header as eh
unicode_data= u''.join(
str_data.decode(codec or 'ascii')
for str_data, codec
in eh.decode_header('=?ISO-8859-7?B?0OXm7/Dv8d/hIPP07+0gyuno4enx/u3h?='))
# unicode_data now is u'Πεζοπορία στον Κιθαιρώνα'
你应该在这里使用unicode_data。不过,如果你(觉得你)需要UTF-8编码的字符串,你可以:
utf8data= unicode_data.encode('utf-8')
更新:我修改了.decode
的调用,以处理codec
为None
的情况(例如eh.decode_header('plain text')
)