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/3973963/

相关文章:

ruby - 使用ruby mail gem获取电子邮件正文而不获取附件

Perl 创建 SSL 套接字在 1020 个套接字后失败并显示 "Bad hostname"

java - 从databricks连接到数据库时获取java.lang.ClassNotFoundException : com. mysql.jdbc.Driver

python - Pandas 合并101

python - 一起替换多个正则表达式模式

ios - 使用 Alamofire 解析 JSON 问题

python - 使用 BeautifulSoup 获取 span 标签的值

python - 使用 Python API 进行逻辑回归多类分类

c++ - 使用 C++ 解析文件,将值加载到结构中

email - 如何使用 imap 命令获取带有部件号的邮件结构