繁体   English   中英

如何解析 Python 中的树?

[英]How to parsing trees in Python?

我需要帮助来开发我正在研究的这个算法。 我有以下格式的树的输入:

Root -> AB CD
AB -> ABC CBA
CD -> CDE FGH

该算法应该读取括号格式并给出以下 output:

                    Root
                     |
                ____________
              AB           CD
              |             |  
       __________         ___________
      ABC      CBA        CDE      FGH

也许你可以从networkx模块开始

  1. 安装网络x: pip pip install networkx

  2. 安装matplotlibpip install matplotlib

  3. 程序

import networkx as nx
import matplotlib.pyplot as plt

if __name__ == "__main__":
    # define DiGraph
    tree = nx.DiGraph()

    # add node
    tree.add_node("root")
    tree.add_node("AB")
    tree.add_node("CD")
    tree.add_node("ABC")
    tree.add_node("CBA")
    tree.add_node("CDE")
    tree.add_node("FGH")

    # add connection edge
    tree.add_edge("root","AB")
    tree.add_edge("root","CD")
    tree.add_edge("AB","ABC")
    tree.add_edge("AB","CBA")
    tree.add_edge("CD","CDE")
    tree.add_edge("CD","FGH")

    # output the tree
    nx.draw(tree,with_labels = True)
    plt.show()

树

暂无
暂无

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

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