python - 从字符串中读取 Bunch()

标签 python json parsing dictionary bunch

我在报告文件中有以下字符串:

"Bunch(conditions=['s1', 's2', 's3', 's4', 's5', 's6'], durations=[[30.0], [30.0], [30.0], [30.0], [30.0], [30.0]], onsets=[[172.77], [322.77], [472.77], [622.77], [772.77], [922.77]])"

我想把它变成一个 Bunch() 对象或一个 dict,这样我就可以访问里面的信息(通过 my_var.conditions my_var["conditions"]).

这与 eval() 配合得很好:

eval("Bunch(conditions=['s1', 's2', 's3', 's4', 's5', 's6'], durations=[[30.0], [30.0], [30.0], [30.0], [30.0], [30.0]], onsets=[[172.77], [322.77], [472.77], [622.77], [772.77], [922.77]])")

但是我想避免使用它。

我尝试编写几个字符串替换,以便将其转换为 dict 语法,然后使用 json.loads() 解析它,但这看起来非常 hackish,并且会中断一旦我在未来的字符串中遇到任何新字段;例如:

"{"+"Bunch(conditions=['s1', 's2', 's3', 's4', 's5', 's6'], durations=[[30.0], [30.0], [30.0], [30.0], [30.0], [30.0]], onsets=[[172.77], [322.77], [472.77], [622.77], [772.77], [922.77]])"[1:-1]+"}".replace("conditions=","'conditions':")

你明白了。

你知道有没有更好的方法来解析这个?

最佳答案

此 pyparsing 代码将为您的 Bunch 声明定义一个解析表达式。

from pyparsing import (pyparsing_common, Suppress, Keyword, Forward, quotedString, 
    Group, delimitedList, Dict, removeQuotes, ParseResults)

# define pyparsing parser for the Bunch declaration
LBRACK,RBRACK,LPAR,RPAR,EQ = map(Suppress, "[]()=")
integer = pyparsing_common.integer
real = pyparsing_common.real
ident = pyparsing_common.identifier

# define a recursive expression for nested lists
listExpr = Forward()
listItem = real | integer | quotedString.setParseAction(removeQuotes) | Group(listExpr)
listExpr << LBRACK + delimitedList(listItem) + RBRACK

# define an expression for the Bunch declaration
BUNCH = Keyword("Bunch")
arg_defn = Group(ident + EQ + listItem)
bunch_decl = BUNCH + LPAR + Dict(delimitedList(arg_defn))("args") + RPAR

这是针对您的示例输入运行的解析器:

# run the sample input as a test
sample = """Bunch(conditions=['s1', 's2', 's3', 's4', 's5', 's6'],
                  durations=[[30.0], [30.0], [30.0], [30.0], [30.0], [30.0]],
                  onsets=[[172.77], [322.77], [472.77], [622.77], [772.77], [922.77]])"""
bb = bunch_decl.parseString(sample)
# print the parsed output as-is
print(bb)

给予:

['Bunch', [['conditions', ['s1', 's2', 's3', 's4', 's5', 's6']], 
    ['durations', [[30.0], [30.0], [30.0], [30.0], [30.0], [30.0]]], 
    ['onsets', [[172.77], [322.77], [472.77], [622.77], [772.77], [922.77]]]]]

使用 pyparsing,你还可以添加一个解析时回调,这样 pyparsing 就会为你做 tokens->Bunch 转换:

# define a simple placeholder class for Bunch
class Bunch(object):
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
    def __repr__(self):
        return "Bunch:(%s)" % ', '.join("%r: %s" % item for item in vars(self).items())

# add this as a parse action, and pyparsing will autoconvert the parsed data to a Bunch
bunch_decl.addParseAction(lambda t: Bunch(**t.args.asDict()))

现在解析器会给你一个实际的 Bunch 实例:

[Bunch:('durations': [[30.0], [30.0], [30.0], [30.0], [30.0], [30.0]], 
        'conditions': ['s1', 's2', 's3', 's4', 's5', 's6'], 
        'onsets': [[172.77], [322.77], [472.77], [622.77], [772.77], [922.77]])]

关于python - 从字符串中读取 Bunch(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37669160/

相关文章:

python - 设置 Tkinter/ttk 框架背景颜色

javascript - Django:找到用户时突出显示表行

java - 在 Java/Android 中解析多个 JSON 数组

php - 将带有媒体查询和其他最终情况的 css 解析为 php 数组

python - 在 Amazon EMR 上安装 PIG 0.14

python - Python 生成器表达式中的变量范围

json - 核心 OWASP ModSecurity - 允许 JSON

java - 从 JSON 数组中提取数据

java - 如何在 Java 中解析多维 JSON 字符串

java - 以 (yyyy-MM-dd) 格式解析字符串日期