如何生成
  • 使用 python 或其他语言不使用递归树?

发布于 2024-09-01 15:56:47 字数 349 浏览 4 评论 0原文

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>
class tree:
    def __init__(self, name='a', childs=[]):
        self.name = name
        self.childs = childs

output:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

乖不如嘢 2024-09-08 15:56:47

要生成没有递归的嵌套列表,您只需跟踪嵌套级别,当您遍历更深的嵌套级别时递增它,并当您向上遍历时递减它。

对于处理诸如结束标记之类的事情,自然的方法是维护一个简单的堆栈(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 工具比我在本示例中所做的任何粗略文本修改更适合该任务。在 Yahoo 或 Google 上搜索:Python“生成 HTML” 将返回数千个页面,介绍执行此操作的方法以及许多可用的工具。

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

To generate nested lists without recursion you'd simply keep track of your nesting level, incrementing it as you traverse into deeper levels of nesting and decrementing it as you traverse back upwards.

The natural approach, for handling things like closing tags, would be to maintain a simple stack (Python list) and push the closing tags onto it as you insert their corresponding opening tags into the output stream. You'd then pop these off as you traverse out of any level of nesting.

You don't say anything about your input format ... so let's pretend that it looks something like:

= Introduction
== Sub Intro
= Module 1

Then something like:

 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

... should do the trick (albeit, rather crudely).

Note that I'm not actually enforcing a rule that one should only increase the nesting level in increments of one. Degenerate input that go from = to ====== in one step would generate extraneous tags and push extraneous tags into the closing stack.

Note: I'm only answering the explicit question about how to handle nesting without recursion. One might infer from your example (using HTML unordered list tags) that your real goal is to generate valid HTML. In that case there are a wealth of Python tools that are far better suited to that task then any crude text munging I'm doing in this example. A Yahoo or Google search on: Python "generate HTML" will return many thousands of pages about ways to do this and the many available tools for this.

(I remember that I used HTMLgen years ago, and I see that it's still available as a Debian package, but it seems to have fallen off of PyPI ... the Python Package Index. There are undoubtedly much more recently updated packages out there. Most people seem to use templating engines such as Genshi or Mako, for example).

鸠书 2024-09-08 15:56:47

也许是这样的:

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])

Maybe something like this:

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])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文