Using 默认字典 https://docs.python.org/2/library/collections.html#collections.defaultdict来自收藏品 https://docs.python.org/2/library/collections.html#module-collections标准库使许多具有层次结构的问题变得简单且可解决。因此,我为您的问题开发了一个示例解决方案。但在运行脚本之前,请确保您有逗号分隔的 csv 文件(名为 test.csv),或者您可以更改csv阅读器 https://docs.python.org/3.5/library/csv.html#module-csv逻辑就在那里。
这是我测试过脚本的 csv 文件。
condition, target, sub, dub
oxygen,tree,G1,T1
oxygen,tree,G2,T1
oxygen,tree,G2,T2
water,car,G3,T1
water,tree,GZ,T1
water,tree,GZ,T2
fire,car,GTD,T3
oxygen,bomb,GYYS,T1
从技术上讲,该脚本应该适用于任何类型、具有各种尺寸的 csv 文件。但你需要亲自测试一下才能确定。
import csv
from collections import defaultdict
def ctree():
""" One of the python gems. Making possible to have dynamic tree structure.
"""
return defaultdict(ctree)
def build_leaf(name, leaf):
""" Recursive function to build desired custom tree structure
"""
res = {"name": name}
# add children node if the leaf actually has any children
if len(leaf.keys()) > 0:
res["children"] = [build_leaf(k, v) for k, v in leaf.items()]
return res
def main():
""" The main thread composed from two parts.
First it's parsing the csv file and builds a tree hierarchy from it.
Second it's recursively iterating over the tree and building custom
json-like structure (via dict).
And the last part is just printing the result.
"""
tree = ctree()
# NOTE: you need to have test.csv file as neighbor to this file
with open('test.csv') as csvfile:
reader = csv.reader(csvfile)
for rid, row in enumerate(reader):
# skipping first header row. remove this logic if your csv is
# headerless
if rid == 0:
continue
# usage of python magic to construct dynamic tree structure and
# basically grouping csv values under their parents
leaf = tree[row[0]]
for cid in range(1, len(row)):
leaf = leaf[row[cid]]
# building a custom tree structure
res = []
for name, leaf in tree.items():
res.append(build_leaf(name, leaf))
# printing results into the terminal
import json
print(json.dumps(res))
# so let's roll
main()
这是结果中的 json 段:
{
"name": "oxygen",
"children": [
{
"name": "tree",
"children": [
{
"name": "G2",
"children": [
{
"name": "T2"
},
{
"name": "T1"
}
]
},
{
"name": "G1",
"children": [
{
"name": "T1"
}
]
}
]
},
{
"name": "bomb",
"children": [
{
"name": "GYYS",
"children": [
{
"name": "T1"
}
]
}
]
}
]
}
如果您还有任何其他疑问和问题,请告诉我。
快乐蟒蛇;)