简体   繁体   English

Python:字典到Web文件列表

[英]Python: Dictionnary to web file list

I have a dict representation of a filesystem, which looks like this. 我有一个文件系统的字典表示形式,看起来像这样。

{
    "en": {
        'file_name_1': [{meta representation of file_name_1}] or False,
        {'folder_name': {
            'index': [{meta repr. of the index}] or False
            'sub_file_1': [{meta repr. of file_name_1}] or False,
            }
        }
    }
    "fr": {
        <...>
    }
    'tree_root': path to the tree's parent node
}

Given the path to one leaf in this tree (file or folder), I would like to represent the tree leading to that leaf as HTML nested lists. 给定该树(文件或文件夹)中一个叶子的路径,我想将通往该叶子的树表示为HTML嵌套列表。

I do not believe my tree will ever become very deep, but for the sake of being fast, I am considering running only once through the path of the leaf. 我不相信我的树会变得很深,但是为了快速起见,我考虑只在叶子的路径上跑一次。

Here is what I have now: ( self.tree is my dictionary, leaf_path my, hmm. leaf path. I tried and cleaned my code for simplicity) 这是我现在所拥有的:( self.tree是我的字典, leaf_path我,hmm。叶子路径。为简单起见,我尝试并清理了代码)

rel_URI = [key for key in leaf_path.split(os.sep)]
stack = []

html = u'<ul>'
for key in rel_URI:
    stack.append(key)
    obj = reduce(dict.get, stack, self.tree)
    if isinstance(obj, dict): # a subdir
        html += u'<ul>'
        for _dir in obj.iterkeys() if isinstance(_dir, dict):
            if _dir == rel_URI[len(stack)]: # in the leaf_path
                html += u'<li class="folder">%s</li>' % self.getTitle(obj, _dir)
            else: # not in the leaf_path
                html += u'<li class="folder, far">%s</li>'% self.getTitle(obj,_dir)
        for _file in obj.iterkeys() if isinstance(_file, list):
            html += u'<li class="file, far">%s</li>'% obj[0]['title']
        html += u'</ul>'
    else: # the leaf file
        item = u'<li class="file">%s</li>' % obj[0]['title']
html += '</ul>'

I have trouble figuring out how to nest the next sub-tree into the iteration: the way it is I have entirely disconnected the next step from this one, and so I end up with a messed-up nested file list. 我在弄清楚如何将下一个子树嵌套到迭代中时遇到了麻烦:按照这种方式,我已完全将下一步与该子树断开连接,因此最终得到了一个混乱的嵌套文件列表。

  • Part of my trouble is that dicts are not ordered 我的麻烦之一是没有下达命令

How would you go about building the list? 您将如何建立清单?

So, following Hans's advice, I turned to OrderedDicts, from the collections module 因此,按照汉斯的建议,我从集合模块转到了OrderedDicts

from collections import OrderedDict

then build OrderedDicts explicitly instead of dicts. 然后显式构建OrderedDicts而不是dict。 They are not prettyprintable, and so harder to debug, but they do the job right. 它们不是可打印的,因此很难调试,但是它们做得很好。

So, thanks Hans. 所以,谢谢汉斯。

I also ended up using recursion after all to place the lists in the right place. 我还最终使用了递归将列表放置在正确的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM