【问题标题】:How to convert a file path into treeview?如何将文件路径转换为树视图?
【发布时间】:2015-08-05 23:32:59
【问题描述】:

现在我在 python 中有一些文件具有以下文件路径格式:

a/b/c/d/e/file1
a/b/c/d/e/file2
a/f/g/h/i/file3
a/f/g/h/i/file4

现在,当我在 Python 中获取这些路径时,我想将其转换为第三方 jquery 插件(例如,fancytree、jqxTree)可以读取的 JSON 格式,以便将其转换为树视图。也许还有其他更简单的方法可以做到这一点,请建议。谢谢!

【问题讨论】:

    标签: javascript jquery python treeview fancytree


    【解决方案1】:

    从 Python 中,您可以按如下方式生成所需的 JSON(请注意,如果您只是跨行传送 JSON,则不需要缩进和排序,但它们使输出可读以进行调试):

    import collections
    import json
    
    myfiles = '''
        a/b/c/d/e/file1
        a/b/c/d/e/file2
        a/f/g/h/i/file3
        a/f/g/h/i/file4
    '''
    
    # Convert to a list
    myfiles = myfiles.split()
    
    
    def recursive_dict():
        """
        This function returns a defaultdict() object
        that will always return new defaultdict() objects
        as the values for any non-existent dict keys.
        Those new defaultdict() objects will likewise
        return new defaultdict() objects as the values
        for non-existent keys, ad infinitum.
        """
        return collections.defaultdict(recursive_dict)
    
    
    def insert_file(mydict, fname):
        for part in fname.split('/'):
            mydict = mydict[part]
    
        # If you want to record that this was a terminal,
        # you can do something like this, too:
        # mydict[None] = True
    
    topdict = recursive_dict()
    for fname in myfiles:
        insert_file(topdict, fname)
    
    print(json.dumps(topdict, sort_keys=True,
                    indent=4, separators=(',', ': ')))
    

    此代码生成以下输出:

    {
        "a": {
            "b": {
                "c": {
                    "d": {
                        "e": {
                            "file1": {},
                            "file2": {}
                        }
                    }
                }
            },
            "f": {
                "g": {
                    "h": {
                        "i": {
                            "file3": {},
                            "file4": {}
                        }
                    }
                }
            }
        }
    }
    

    【讨论】:

    • def recursive_dict(): return collections.defaultdict(recursive_dict) 是做什么的?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多