使用defaultdict从馆藏标准库赚了很多的具有层次结构简单,可解决的问题。因此,我为您的问题开发了示例解决方案。但是在运行脚本之前,请确保已用逗号分隔了csv文件(名为test.csv),或者可以在此处更改csv阅读器逻辑。
这是我测试脚本的csv文件。
condition, target, sub, duboxygen,tree,G1,T1oxygen,tree,G2,T1oxygen,tree,G2,T2water,car,G3,T1water,tree,GZ,T1water,tree,GZ,T2fire,car,GTD,T3oxygen,bomb,GYYS,T1
从技术上讲,该脚本应适用于具有各种尺寸的任何类型的csv文件。但是您需要自己进行测试才能确定。
import csvfrom collections import defaultdictdef 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 resdef 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 rollmain()这是结果的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" } ] } ] } ] }请让我知道是否还有其他问题。快乐的pythonning;)



