【问题标题】:Decoding NNTP headers from (UTF-8?)从 (UTF-8?) 解码 NNTP 标头
【发布时间】:2019-12-02 22:06:27
【问题描述】:

我正在编写一些 Python 3 代码来获取 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

【问题讨论】:

  • 您确定显示的消息实际上是罪魁祸首吗?异常指出,问题发生在字符串b"Ana\xefs's"
  • @omni 实际上=?UTF-8?B?QW5h73Mncw==?=b"Ana\xefs's",一旦它被解码(电子邮件不能真正在标题中直接包含utf,所以还有另一种编码为只使用ascii的东西) .见RFC-2047

标签: python utf nntp


【解决方案1】:

这里的问题是你的输入实际上是无效的。

这个字符串就是问题所在:

'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"

【讨论】:

    猜你喜欢
    • 2013-06-15
    • 2012-10-23
    • 1970-01-01
    • 2012-11-07
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 2011-07-19
    相关资源
    最近更新 更多