前言:为了帮助解释我为什么要这样做,我将解释最终目标。实际上,我有一个用非常特殊的语法定义的帐户列表。以下是一些示例:Assets:Bank:Car
Assets:Bank:House
Assets:Savings:Emergency
Assets:Savings:Goals:Roof
Assets:Reserved
如上所示,一个帐户可以有任意数量的父母和子女。最终目标是用Python将上述帐户解析为一个树结构,该结构将用于在Sublime文本编辑器中提供帐户自动完成(即,如果我键入Assets:,然后查询auto complete,我将看到一个列表,如下所示:Bank,Savings,Reserved)
结果:使用序言中的account list,Python中所需的结果如下所示:
^{pr2}$
半解:我可以使用递归将两个基本帐户相加。这适用于添加这两个:Assets:Bank:Car和Assets:Bank:House。然而,一旦它们开始不同,它就开始崩溃,递归变得混乱,所以我不确定这是否是最好的方法。在import re
def parse_account(account_str):
subs = account_str.split(":")
def separate(subs):
if len(subs) == 1:
return subs
elif len(subs):
return [{subs[0]: separate(subs[1:])}]
return separate(subs)
def merge_dicts(a, b):
# a will be a list with dictionaries and text values and then nested lists/dictionaries/text values
# b will always be a list with ONE dictionary or text value
key = b[0].keys()[0] # this is the dictionary key of the only dictionary in the b list
for item in a: # item is a dictionary or a text value
if isinstance(item, dict): # if item is a dictionary
if key in item:
# Is the value a list with a dict or a list with a text value
if isinstance(b[0][key][0], str):
# Extend the current list with the new value
item[key].extend(b[0][key])
else:
# Recurse to the next child
merge_dicts(item[key], b[0][key])
else:
return a
# Accounts have an "open [name]" syntax for defining them
text = "open Assets:Bank:Car\nopen Assets:Bank:House\nopen Assets:Savings:Emergency\nopen Assets:Savings:Goals:Roof\nopen Assets:Reserved"
EXP = re.compile("open (.*)")
accounts = EXP.findall(text) # This grabs all accounts
# Create a list of all the parsed accounts
dicts = []
for account in accounts:
dicts.append(parse_account(account))
# Attempt to merge two accounts together
final = merge_dicts(dicts[0], dicts[1])
print final
# In the future we would call: reduce(merge_dicts, dicts) to merge all accounts
我可能会以完全错误的方式去做这件事,我会对不同的意见感兴趣。否则,是否有人了解如何使用示例字符串中的其余帐户进行此操作?在