【发布时间】:2023-03-29 03:26:01
【问题描述】:
我有一个如下的 json 文件:
{
"App Builder": {
"utterance": [
"create an app",
"create app for me",
"can you create an application?"
],
"question": [
"Do you want to create application through UI or API Builder?",
"Do you want to try our getting started page?"
],
"children": [{
"API Builder": {
"utterance": [
"create an app using API Buider",
"make an application using API Builder",
"create API Builder application"
]
}
},
{
"UI": {
"utterance": [
"create an app using user interface",
"make an application using UI",
"create UI application"
],
"question": [
"Do you want to create application through Template or UI Builder?",
"Do you want to try our getting started page?"
]
,
"children": [{
"UI Builder": {
"utterance": [
"create an app using UI Buider",
"make an application using UI Builder",
"create UI Builder application"
]
}
},
{
"Template": {
"utterance": [
"create an app using Template",
"make an application using Template",
"create Template application"
],
"question": [
"Do you want to create application through Angular or React or PHP?",
"Do you want to try our getting started page?"
],
"children": [{
"Angular": {
"utterance": [
"create an app using Angular",
"make an application using Angular template",
"create Angular application"
]
}
}, {
"React": {
"utterance": [
"create an app using React",
"make an application using template React",
"create React application"
]
}
}, {
"PHP": {
"utterance": [
"create an app using PHP",
"make an application using template PHP",
"create PHP application"
]
}
}]
}
}
]
}
}
]
}
}
由此,我想找到每个节点的所有行。通过使用下面的代码,我设法得到了下面给出的结果。
edges = []
leaves = []
nodes = []
def get_edges(treedict, parent=None):
try:
name = next(iter(treedict.keys()))
nodes.append(name)
if parent is not None:
edges.append((parent, name))
for item in treedict[name]["children"]:
if isinstance(item, dict):
get_edges(item, parent=name)
else:
edges.append((name, item))
except KeyError as e:
leaves.append(name)
pass
中间结果:
print(edges)
[('App Builder', 'API Builder'), ('App Builder', 'UI'), ('UI', 'UI Builder'), ('UI', 'Template'), ('Template', 'Angular'), ('Template', 'React'), ('Template', 'PHP')]
现在我想找到每个节点的路径。即,
['App Builder', 'App Builder/API Builder', 'App Builder/UI', 'App Builder/UI/UI Builder', 'App Builder/UI/Template',
'App Builder/UI/Template/Angular', 'App Builder/UI/Template/React', 'App Builder/UI/Template/PHP']
我怎样才能得到这些值?
我只能通过将列表转换为树来从edges 获取此路径吗?
还有其他更好的方法来解决这个问题吗?
任何帮助都将是可观的。
【问题讨论】:
-
This SO 帖子可以帮助您。
标签: python json python-3.x python-2.7 tree