python - 高效地将扁平字符串解析为嵌套字典
python - Efficiently parsing flattened strings into nested dictionaries
我正在从专有数据库中获取目录和项目列表。列表也可以是巨大的,包含数千个视图和各种嵌套。列表示例:
"MIPK",
"MIPK\/CM.toroidal",
"MIPK\/CM.Supervoid",
"MIPK\/DORAS",
"MIPK\/DORAS\/CRUDE",
"MIPK\/DORAS\/CRUDE\/CM.forest",
"MIPK\/DORAS\/CRUDE\/CM.benign",
"MIPK\/DORAS\/CRUDE\/CM.dunes",
"MIPK\/DORAS\/COMMODITIES",
"MIPK\/DORAS\/COMMODITIES\/CRUDE",
"MIPK\/DORAS\/COMMODITIES\/CRUDE\/CM.tangeant",
"MIPK\/DORAS\/COMMODITIES\/CRUDE\/CM.astral",
"MIPK\/DORAS\/COMMODITIES\/CRUDE\/CM.forking"
目录用 \/
大写分隔,混合大小写表示项目。
我现在返回的JSon是这样的:
{
"contents": [{
"root_path": "MIPK",
"root_name": "MIPK",
"directories": [{
"subd_name": "DORAS",
"subd_path": "MIPK.DORAS"
}],
"views": [{
"view_name": "CM.toroidal"
},
{
"view_name": "CM.Supervoid"
}
]
}, {
"root_path": "MIPK.DORAS",
"root_name": "DORAS",
"directories": [{
"subd_name": "CRUDE",
"subd_path": "MIPK.DORAS.CRUDE"
},
{
"subd_name": "COMMODITIES",
"subd_path": "MIPK.DORAS.COMMODITIES"
}
],
"views": []
}, {
"root_path": "MIPK.DORAS.CRUDE",
"root_name": "CRUDE",
"directories": [],
"views": [{
"view_name": "CM.forest"
},
{
"view_name": "CM.benign"
},
{
"view_name": "CM.dunes"
}
]
}, {
"root_path": "MIPK.DORAS.COMMODITIES",
"root_name": "COMMODITIES",
"directories": [{
"subd_name": "CRUDE",
"subd_path": "MIPK.DORAS.COMMODITIES.CRUDE"
}],
"views": []
}, {
"root_path": "MIPK.DORAS.COMMODITIES.CRUDE",
"root_name": "CRUDE",
"directories": [],
"views": [{
"view_name": "CM.tangeant"
},
{
"view_name": "CM.astral"
},
{
"view_name": "CM.forking"
}
]
}]
}
当前代码:
import logging
import copy
import time
def fetch_resources(input_resources_list):
'''
:return: Json list of dictionaries each dictionary element containing:
Directory name, directory path, list of sub-directories, list of views
resource_list is a flattened list produced by a database walk function
'''
start = time.time()
resources = {
'contents': [{}]
}
for item in input_resources_list:
# Parsing list into usable pieces
components = item.rsplit('\', 1)
if len(components) == 1:
# Handles first element
root_dict = {'root_path': components[0],
'root_name': components[-1],
'directories': [],
'views': []
}
resources['contents'][0].update(root_dict)
else:
# Enumerate resources in list so search by key value can be done and then records can be appended.
for ind, content in enumerate(copy.deepcopy(resources['contents'])):
if resources['contents'][ind]['root_path'] == components[0]:
# Directories are upper case, adds a new entry if
if clean_item.isupper() :
root_dict = {'root_path': components[0],
'root_name': components[-1],
'directories': [],
'views': []
}
resources['contents'].append(root_dict)
sub_dict = {'subd_path': components[0],
'subd_name': components[-1]}
resources['contents'][ind]['directories'].append(sub_dict)
elif clean_item.isupper() == False :
resources['contents'][ind]['views'] \
.append({'view_name':components[-1]})
print 'It took {}'.format((time.time() - start)*1000)
return resources
这适用于小型工作负载(大约 100-500),但不适用于 000 的目标工作负载。
如何针对时间优化方法?
目前为输入列表中的每个项目重建枚举循环,以便按 root_path
键值进行搜索。有没有更简单的方法来搜索字典列表中的键值并将条目附加到该条目目录和视图列表?
您在构建这些字符串时丢弃了很多信息。例如,当你看到 MIPK\/DORAS
时,无法知道它是一个文件(它应该只是父目录列表中的一个字符串),一个叶目录(它应该是父目录的字典中的一个列表) ,或中间目录(应该是父目录字典中的字典)。你能做的最好的事情(没有二次嵌套搜索)就是猜测,如果你猜错了,稍后再改。
此外,有时您的中间目录甚至不会自己显示,而只是作为后面路径的组成部分出现,但有时它们会出现。所以有时你必须修复的“猜测”将是根本不存在的目录。
最后,如果您想要的格式不明确,例如,any directly 可以同时包含文件和目录(应该是字典或列表),或者什么都没有(应该是空字典、空列表,还是只是一个字符串?)。
然而,事情似乎是有序的,模棱两可的情况似乎并没有真正出现。如果我们可以依赖这两者,我们可以通过查看它是前缀还是下一个条目来判断某物是否是目录。然后我们可以读取叶子并将它们放入 0 个或多个嵌套字典中的列表中的字符串集合。
所以,首先,我们要迭代相邻的路径对,以便更容易做到“它是下一个值的前缀吗?”检查:
output = {}
it1, it2 = itertools.tee(paths)
next(it2)
pairs = itertools.zip_longest(it1, it2, fillvalue='')
for path, nextpath in pairs:
if nextpath.startswith(path):
continue
现在,我们知道 path
是一片叶子,所以我们需要找到要将其附加到的列表,如果需要则创建一个,这可能意味着沿途递归创建字典:
components = path.split(r'\/')
d = output
for component in components[:-2]:
d = d.setdefault(component, {})
d.setdefault(components[-2], []).append(components[-1])
我还没有测试过这个,但它应该对明确的输入做正确的事情,但是如果任何目录同时包含文件和子目录,或者任何顶级目录包含文件,或者任何其他不明确的情况(空目录除外,空目录将被视为与文件相同)。
当然,这有点丑陋,但这是解析一种丑陋格式所固有的,这种格式依赖于许多特殊情况规则来处理本来会模棱两可的内容。
我正在从专有数据库中获取目录和项目列表。列表也可以是巨大的,包含数千个视图和各种嵌套。列表示例:
"MIPK",
"MIPK\/CM.toroidal",
"MIPK\/CM.Supervoid",
"MIPK\/DORAS",
"MIPK\/DORAS\/CRUDE",
"MIPK\/DORAS\/CRUDE\/CM.forest",
"MIPK\/DORAS\/CRUDE\/CM.benign",
"MIPK\/DORAS\/CRUDE\/CM.dunes",
"MIPK\/DORAS\/COMMODITIES",
"MIPK\/DORAS\/COMMODITIES\/CRUDE",
"MIPK\/DORAS\/COMMODITIES\/CRUDE\/CM.tangeant",
"MIPK\/DORAS\/COMMODITIES\/CRUDE\/CM.astral",
"MIPK\/DORAS\/COMMODITIES\/CRUDE\/CM.forking"
目录用 \/
大写分隔,混合大小写表示项目。
我现在返回的JSon是这样的:
{
"contents": [{
"root_path": "MIPK",
"root_name": "MIPK",
"directories": [{
"subd_name": "DORAS",
"subd_path": "MIPK.DORAS"
}],
"views": [{
"view_name": "CM.toroidal"
},
{
"view_name": "CM.Supervoid"
}
]
}, {
"root_path": "MIPK.DORAS",
"root_name": "DORAS",
"directories": [{
"subd_name": "CRUDE",
"subd_path": "MIPK.DORAS.CRUDE"
},
{
"subd_name": "COMMODITIES",
"subd_path": "MIPK.DORAS.COMMODITIES"
}
],
"views": []
}, {
"root_path": "MIPK.DORAS.CRUDE",
"root_name": "CRUDE",
"directories": [],
"views": [{
"view_name": "CM.forest"
},
{
"view_name": "CM.benign"
},
{
"view_name": "CM.dunes"
}
]
}, {
"root_path": "MIPK.DORAS.COMMODITIES",
"root_name": "COMMODITIES",
"directories": [{
"subd_name": "CRUDE",
"subd_path": "MIPK.DORAS.COMMODITIES.CRUDE"
}],
"views": []
}, {
"root_path": "MIPK.DORAS.COMMODITIES.CRUDE",
"root_name": "CRUDE",
"directories": [],
"views": [{
"view_name": "CM.tangeant"
},
{
"view_name": "CM.astral"
},
{
"view_name": "CM.forking"
}
]
}]
}
当前代码:
import logging
import copy
import time
def fetch_resources(input_resources_list):
'''
:return: Json list of dictionaries each dictionary element containing:
Directory name, directory path, list of sub-directories, list of views
resource_list is a flattened list produced by a database walk function
'''
start = time.time()
resources = {
'contents': [{}]
}
for item in input_resources_list:
# Parsing list into usable pieces
components = item.rsplit('\', 1)
if len(components) == 1:
# Handles first element
root_dict = {'root_path': components[0],
'root_name': components[-1],
'directories': [],
'views': []
}
resources['contents'][0].update(root_dict)
else:
# Enumerate resources in list so search by key value can be done and then records can be appended.
for ind, content in enumerate(copy.deepcopy(resources['contents'])):
if resources['contents'][ind]['root_path'] == components[0]:
# Directories are upper case, adds a new entry if
if clean_item.isupper() :
root_dict = {'root_path': components[0],
'root_name': components[-1],
'directories': [],
'views': []
}
resources['contents'].append(root_dict)
sub_dict = {'subd_path': components[0],
'subd_name': components[-1]}
resources['contents'][ind]['directories'].append(sub_dict)
elif clean_item.isupper() == False :
resources['contents'][ind]['views'] \
.append({'view_name':components[-1]})
print 'It took {}'.format((time.time() - start)*1000)
return resources
这适用于小型工作负载(大约 100-500),但不适用于 000 的目标工作负载。
如何针对时间优化方法?
目前为输入列表中的每个项目重建枚举循环,以便按
root_path
键值进行搜索。有没有更简单的方法来搜索字典列表中的键值并将条目附加到该条目目录和视图列表?
您在构建这些字符串时丢弃了很多信息。例如,当你看到 MIPK\/DORAS
时,无法知道它是一个文件(它应该只是父目录列表中的一个字符串),一个叶目录(它应该是父目录的字典中的一个列表) ,或中间目录(应该是父目录字典中的字典)。你能做的最好的事情(没有二次嵌套搜索)就是猜测,如果你猜错了,稍后再改。
此外,有时您的中间目录甚至不会自己显示,而只是作为后面路径的组成部分出现,但有时它们会出现。所以有时你必须修复的“猜测”将是根本不存在的目录。
最后,如果您想要的格式不明确,例如,any directly 可以同时包含文件和目录(应该是字典或列表),或者什么都没有(应该是空字典、空列表,还是只是一个字符串?)。
然而,事情似乎是有序的,模棱两可的情况似乎并没有真正出现。如果我们可以依赖这两者,我们可以通过查看它是前缀还是下一个条目来判断某物是否是目录。然后我们可以读取叶子并将它们放入 0 个或多个嵌套字典中的列表中的字符串集合。
所以,首先,我们要迭代相邻的路径对,以便更容易做到“它是下一个值的前缀吗?”检查:
output = {}
it1, it2 = itertools.tee(paths)
next(it2)
pairs = itertools.zip_longest(it1, it2, fillvalue='')
for path, nextpath in pairs:
if nextpath.startswith(path):
continue
现在,我们知道 path
是一片叶子,所以我们需要找到要将其附加到的列表,如果需要则创建一个,这可能意味着沿途递归创建字典:
components = path.split(r'\/')
d = output
for component in components[:-2]:
d = d.setdefault(component, {})
d.setdefault(components[-2], []).append(components[-1])
我还没有测试过这个,但它应该对明确的输入做正确的事情,但是如果任何目录同时包含文件和子目录,或者任何顶级目录包含文件,或者任何其他不明确的情况(空目录除外,空目录将被视为与文件相同)。
当然,这有点丑陋,但这是解析一种丑陋格式所固有的,这种格式依赖于许多特殊情况规则来处理本来会模棱两可的内容。