很有趣。你真的在这件事上对我。。。在def parse(tokens):
""" take iterator of tokens, parse to dictionary or atom """
dictionary = {}
# iterate tokens...
for token in tokens:
if token == ")" or next(tokens) == ")":
# token is ')' -> end of dict; next is ')' -> 'leaf'
break
# add sub-parse to dictionary
dictionary[token] = parse(tokens)
# return dict, if non-empty, else token
return dictionary or int(token)
安装和演示:
^{pr2}$
或者,也可以使用一系列字符串替换将该字符串转换为实际的Python字典字符串,然后对其进行求值,例如:as_dict = eval("{'" + s.replace(")", "'}, ")
.replace("(", "': {'")
.replace(", ", ", '")
.replace(", ''", "")[:-3] + "}")
这将把“leafs”包装在单个字符串集中,例如,{'8'}而不是{},但这应该很容易在后处理步骤中修复。在