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

标签 python parsing imap 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 - 在python imaplib中解析带括号的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12739563/

相关文章:

c++ - PathGetArgs/PathRemoveArgs 与 CommandLineToArgvW - 有区别吗?

java - 在 Java 中解析来自 String 的输入

c# - 在 C# 中使用 AE.Net.Mail 访问 GMail

python - 在 HTML 中同时查找多个 "Text"选项

python - 更改seaborn中箱形图中线的宽度

python - 将列表中的每个第二个数字相乘

python - 如何从API中抓取NHL球队的名称和赔率?

ssl - Emacs wanderlust IMAP 密码验证

java - 无法使用 IMAP 连接到 Gmail

python - 谁能告诉我为什么以下 Python 代码在输出中生成 None ?