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

ite*_*ter 1 python parsing imap imaplib

我正在寻找简单的方法将IMAP响应中出现的括号列表拆分为Python列表或元组.我想要离开

'(BODYSTRUCTURE ("text" "plain" ("charset" "ISO-8859-1") NIL NIL "quoted-printable" 1207 50 NIL NIL NIL NIL))'
Run Code Online (Sandbox Code Playgroud)

(BODYSTRUCTURE, ("text", "plain", ("charset", "ISO-8859-1"), None, None, "quoted-printable", 1207, 50, None, None, None, None))
Run Code Online (Sandbox Code Playgroud)

Pau*_*McG 5

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)
Run Code Online (Sandbox Code Playgroud)

打印:

[['BODYSTRUCTURE', ['"text"', '"plain"', ['"charset"', '"ISO-8859-1"'], 'NIL', 'NIL', '"quoted printable"', '1207', '50', 'NIL', 'NIL', 'NIL', 'NIL']]]
Run Code Online (Sandbox Code Playgroud)

这是一个稍微修改过的解析器,它将整数字符串的解析时转换为整数,从"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)
Run Code Online (Sandbox Code Playgroud)

打印:

[['BODYSTRUCTURE', ['text', 'plain', ['charset', 'ISO-8859-1'], None, None, 'quoted-printable', 1207, 50, None, None, None, None]]]
Run Code Online (Sandbox Code Playgroud)