如何在不使用python或其他语言递归的情况下生成<ul> <li>树?</li> </ul>

时间:2010-05-14 02:18:21

标签: python tree

class tree:
    def __init__(self, name='a', childs=[]):
        self.name = name
        self.childs = childs

输出:

<ul>
    <li>
    Introduction
    <ul>
        <li>Sub Intro</li>
    </ul>
    </li>

    <li>Module 1</li>
</ul>

2 个答案:

答案 0 :(得分:2)

要生成没有递归的嵌套列表,您只需跟踪嵌套级别,在遍历更深层次的嵌套时递增它,并在向后移动时递减它。

处理诸如结束标记之类的事情的自然方法是维护一个简单的堆栈(Python列表),并在将相应的开始标记插入输出流时将结束标记推送到它上面。然后,当您遍历任何级别的嵌套时,您都会将它们弹出。

你没有说出你的输入格式...所以让我们假设它看起来像:

= Introduction
== Sub Intro
= Module 1

然后像:

 def pref_txt_to_ul(txt):
    nesting = 0
    closing_tags = list()
    for x in txt:
        if len(x.split()) < 2:
            continue
        prefix, content = x.split(None,1)
        nd = len(prefix)           ## new depth
        assert prefix == "=" * nd  ## First "word" is all = characters

        if nd > nesting:
            print "\n", " " * nesting * 4, "<ul>" * (nd - nesting), ## Push new opening tags into output
            closing_tags.append('</ul>' * (nd - nesting))  ## push closing tags for later
        elif nd < nesting:
            for x in range(nesting - nd):
                if closing_tags:
                    print " " * nesting * 4, closing_tags.pop(),  ## Pop closing tags
        nesting = nd
        print "\n", " " * nesting * 4, "<li>%s</li>" % content,  # push out this item (at new depth)
    ## After all text is done:
    while closing_tags:
        print closing_tags.pop(),   # Pop off remaining cloing tags

......应该做的伎俩(虽然相当粗暴)。

请注意,我实际上并没有强制执行一个规则,即只应以1为增量增加嵌套级别。在一步中从=到======的简并输入将生成无关标签并将无关标签推入结束堆栈。

注意:我只回答有关如何在没有递归的情况下处理嵌套的明确问题。有人可能会从您的示例(使用HTML无序列表标记)推断出您的真正目标是生成有效的HTML。在这种情况下,有大量的Python工具更适合于那个任务,然后在这个例子中我正在做的任何粗略文本。雅虎或谷歌搜索: Python“生成HTML”将返回数千页关于如何执行此操作的页面以及许多可用的工具。

(我记得几年前我使用过HTMLgen,我发现它仍然可以作为Debian软件包使用,但它似乎已经脱离了PyPI ...... Python软件包索引。毫无疑问,最近更新了更新的软件包大多数人似乎都使用模板引擎,例如Genshi或Mako。

答案 1 :(得分:-1)

也许是这样的:

NEW=object()
END=object()

class tree:
    def __init__(self, name='a', childs=[]):
        self.name = name
        self.childs = childs

    def __str__(self):
        indent=0
        result=[]
        for i in self.childs:
            if i is NEW:
                result.append('%s<ul>\n'%('    '*indent))
                indent+=1
            elif i is END:                
                indent-=1
                result.append('%s</ul>\n'%('    '*indent))
            else:
                result.append('%s<li>%s</li>\n'%('    '*indent, i))
        return ''.join(result)



print tree('test', [NEW, 'Introduction', NEW, 'Sub Intro', END, 'Module 1', END])