Skip to main content
 首页 » 编程设计

python之在python imaplib中解析带括号的列表

2025年05月04日24birdshome

我正在寻找一种简单的方法来将来自 IMAP 响应的带括号的列表拆分为 Python 列表或元组。我想从

'(BODYSTRUCTURE ("text" "plain" ("charset" "ISO-8859-1") NIL NIL "quoted-printable" 1207 50 NIL NIL NIL NIL))' 

到

(BODYSTRUCTURE, ("text", "plain", ("charset", "ISO-8859-1"), None, None, "quoted-printable", 1207, 50, None, None, None, None)) 

请您参考如下方法:

pyparsing 的 nestedExpr 解析器函数默认解析嵌套的括号:

from pyparsing import nestedExpr 
 
text = '(BODYSTRUCTURE ("text" "plain" ("charset" "ISO-8859-1") NIL NIL "quotedprintable" 1207 50 NIL NIL NIL NIL))' 
 
print nestedExpr().parseString(text) 

打印:

[['BODYSTRUCTURE', ['"text"', '"plain"', ['"charset"', '"ISO-8859-1"'], 'NIL', 'NIL', '"quoted printable"', '1207', '50', 'NIL', 'NIL', 'NIL', 'NIL']]] 

这是一个稍微修改过的解析器,它在解析时将整数字符串转换为整数,从“NIL”到 None,并从带引号的字符串中去除引号:

from pyparsing import (nestedExpr, Literal, Word, alphanums,  
    quotedString, replaceWith, nums, removeQuotes) 
 
NIL = Literal("NIL").setParseAction(replaceWith(None)) 
integer = Word(nums).setParseAction(lambda t:int(t[0])) 
quotedString.setParseAction(removeQuotes) 
content = (NIL | integer | Word(alphanums)) 
 
print nestedExpr(content=content, ignoreExpr=quotedString).parseString(text) 

打印:

[['BODYSTRUCTURE', ['text', 'plain', ['charset', 'ISO-8859-1'], None, None, 'quoted-printable', 1207, 50, None, None, None, None]]]