在python的imaplib中解析括号列表
作者:互联网
我正在寻找一种简单的方法将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]]]
标签:python,parsing,imap,imaplib 来源: https://codeday.me/bug/20191009/1880221.html