Python file parsing: Build tree from text file

前端 未结 3 1160
慢半拍i
慢半拍i 2020-12-13 20:20

I have an indented text file that will be used to build a tree. Each line represents a node, and indents represent depth as well as node the current node is a child of.

3条回答
  •  心在旅途
    2020-12-13 20:48

    If you don't insist on recursion, this works too:

    from itertools import takewhile
    
    is_tab = '\t'.__eq__
    
    def build_tree(lines):
        lines = iter(lines)
        stack = []
        for line in lines:
            indent = len(list(takewhile(is_tab, line)))
            stack[indent:] = [line.lstrip()]
            print stack
    
    source = '''ROOT
    \tNode1
    \t\tNode2
    \t\t\tNode3
    \t\t\t\tNode4
    \tNode5
    \tNode6'''
    
    build_tree(source.split('\n'))
    

    Result:

    ['ROOT']
    ['ROOT', 'Node1']
    ['ROOT', 'Node1', 'Node2']
    ['ROOT', 'Node1', 'Node2', 'Node3']
    ['ROOT', 'Node1', 'Node2', 'Node3', 'Node4']
    ['ROOT', 'Node5']
    ['ROOT', 'Node6']
    

提交回复
热议问题