我正在编写一些Python3代码来抓取NNTP消息,解析报头,并处理数据。我的代码可以很好地处理前几百条消息,然后抛出一个异常。
例外情况是:
sys.exc_info()
(<class 'UnicodeDecodeError'>, UnicodeDecodeError('utf-8', b"Ana\xefs's", 3, 4, 'invalid continuation byte'), <traceback object at 0x7fe325261c08>)
问题来自于试图解析出主题。消息的原始内容为:
{'subject': 'Re: Mme. =?UTF-8?B?QW5h73Mncw==?= Computer Died', 'from': 'Fred Williams <unclefred@webruler.com>', 'date': 'Sun, 05 Aug 2007 18:55:22 -0400', 'message-id': '<13bclaqcdot4s55@corp.supernews.com>', 'references': '<mq0cb35ci3tv53hnahmnognh2rauqpveqb@4ax.com>', ':bytes': '1353', ':lines': '14', 'xref': 'number1.nntp.dca.giganews.com rec.pets.cats.community:171958'}
那个?UTF-8?是我不知道该怎么处理的。吐在自己身上的代码片段是:
for msgId, msg in overviews:
print(msgId)
hdrs = {}
if msgId == 171958:
print(msg)
try:
for k in msg.keys():
hdrs[k] = nntplib.decode_header(msg[k])
except:
print('Unicode error!')
continue
发布于 2019-12-03 06:58:05
这里的问题是你的输入实际上是无效的。
这个字符串就是问题所在:
'Re: Mme. =?UTF-8?B?QW5h73Mncw==?= Computer Died'
你可以这样做来解码它:
import email.header
email.header.decode_header('Re: Mme. =?UTF-8?B?QW5h73Mncw==?= Computer Died')
结果是:
[(b'Re: Mme. ', None), (b"Ana\xefs's", 'utf-8'), (b' Computer Died', None)]
所以,难看的部分=?UTF-8?B?QW5h73Mncw==?=
是b"Ana\xefs's"
,它应该是一个UTF-8字符串,但它不是有效的UTF-8。
>>> b"Ana\xefs's".decode('utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xef in position 3: invalid continuation byte
这就是您看到的错误。
现在该由你来决定做什么了。例如..。
忽略错误:
>>> b"Ana\xefs's".decode('utf-8', errors='ignore')
"Anas's"
将其标记为错误:
>>> b"Ana\xefs's".decode('utf-8', errors='replace')
"Ana�s's"
胡乱猜测正确的编码:
>>> b"Ana\xefs's".decode('windows-1252')
"Anaïs's"
>>> b"Ana\xefs's".decode('iso-8859-1')
"Anaïs's"
>>> b"Ana\xefs's".decode('iso-8859-2')
"Anaďs's"
>>> b"Ana\xefs's".decode('iso-8859-4')
"Anaīs's"
>>> b"Ana\xefs's".decode('iso-8859-5')
"Anaяs's"
https://stackoverflow.com/questions/59147335
复制相似问题