我想用imaplib搜索特定的邮件,这些邮件的主题包含中文。 我得到了这样的错误:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
所以我用.encode来编码到'UTF-8',我什么也没有得到。打印出来的是
^{pr2}$正确答案应该是71,我通过邮件在收件箱中搜索。 这是我的代码:
import imaplib,email
host = 'imap.263.net'
user = '***@***'
psw = '*****'
count = 0
con = imaplib.IMAP4(host,143)
con.login(user,psw)
con.select('INBOX',readonly =True)
eva = '日报'
# eva = eva.encode('utf-8')
resp,liujf = con.search('UTF-8','SUBJECT','%s'%eva, 'Since','01-Feb-2018')
items = liujf[0].split()
print(len(items))
print(items)
我想应该是unicode的问题。我怎样才能修好它?在
您传入的是一个原始的Unicode字符串,在该字符串中,您应该以UTF-8字节序列的形式传入该字符串。你甚至把它标为UTF-8!这意味着你可能想了解一下两者之间的差异。在
改变
到
^{pr2}$要了解更多背景,可以阅读https://www.unicode.org/faq/utf_bom.html#UTF8和/或https://nedbatchelder.com/text/unipain.html
构造
'%s'%string
只是说string
的一种丑陋和不规则的方式,但这里实际上是一个错误:'%s'%string.encode('utf-8')
生成一个字节字符串,然后将其插入到Unicode字符串中,这会产生完全错误的结果。注意:请注意
'%s'%eva.encode('utf-8')
如何获取编码的字节字符串并将其转换为Unicode表示。注释掉的行显示您尝试了eva = eva.encode('utf-8')
,但是由于在Unicode字符串中不必要的%
插值,结果显然是错误的。在我认为你应该先解码然后再编码中文文字。如果我们把它解释为拉丁语1编码,然后你先解码,再编码。 不包括-伊娃。解码('latin-1')。编码('utf-8')
相关问题 更多 >
编程相关推荐