【问题标题】:Read Bunch() from string从字符串中读取 Bunch()
【发布时间】:2016-10-06 18:05:24
【问题描述】:

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

"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.conditionsmy_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':")

你明白了。

你知道是否有更好的方法来解析这个吗?

【问题讨论】:

  • 您的最终预期输出究竟是什么?另外,您能否展示一下您迄今为止所做的工作,以了解您的方法是什么样的?

标签: python json parsing dictionary bunch


【解决方案1】:

此 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]])]

【讨论】:

  • 请注意!绝佳时机!我刚刚开始考虑在 lex/yacc(Old Dogs 等)中做一个小语法,虽然我真的很想留在 Python 中。我完全忘记了 pyparsing。
  • 如果你真的想使用 lex/yacc,你仍然可以使用 PLY 留在 Python 中。
【解决方案2】:

这是我丑陋的一段代码,请检查:

import re
import json
l = "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]])"

exec('{}="{}"'.format(l[:5],l[6:-1]))
sb = re.split("=| [a-zA-Z]", Bunch)
temp = ['"{}"'.format(x) if x.isalpha() else x for x in sb ]
temp2 = ','.join(temp)
temp3 = temp2.replace('",[', '":[')
temp4 = temp3.replace(',,', ',')
temp5 = temp4.replace("\'", '"')
temp6 = """{%s}""" %(temp5)
rslt = json.loads(temp6)

最终,输出:

rslt
Out[12]: 
{'urations': [[30.0], [30.0], [30.0], [30.0], [30.0], [30.0]],
 'conditions': ['s1', 's2', 's3', 's4', 's5', 's6'],
 'nsets': [[172.77], [322.77], [472.77], [622.77], [772.77], [922.77]]}

rslt["conditions"]
Out[13]: ['s1', 's2', 's3', 's4', 's5', 's6']

一般来说,我认为re是你需要的包,但由于我使用它的经验有限,我可以在这里很好地应用它。希望其他人能给出更优雅的解决方案。

仅供参考,你说你可以很容易地使用eval 来获得你想要的东西,但是当我尝试使用它时,我得到了TypeError: 'str' object is not callable。您使用的是哪个 Python 版本? (我在Python27和Python33上试过,都不能用)

【讨论】:

    猜你喜欢
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    相关资源
    最近更新 更多