Python はネットワークを使用して txt ファイルを読み取り、有向グラフを描画します

class demo():
    def __init__(self):
        self.file_path='test.txt'#图文件    
    def draw_graph(self):

        G2 = nx.DiGraph()  # 创建:空的 有向图
        f = open(self.file_path)
        lines = [l.split() for l in f.readlines() if l.strip()]
        # print(lines)
        for i in lines:
            G2.add_edge(i[0],i[1],weight=i[2])

        pos = nx.random_layout(G2)  # 用 FR算法排列节点
        nx.draw(G2, pos, with_labels=True, alpha=0.5)
        labels = nx.get_edge_attributes(G2, 'weight')
        nx.draw_networkx_edge_labels(G2, pos, edge_labels=labels)
        plt.show()

txt ファイルの形式は次のとおりです。開始点と終了点の重みはスペースで区切られます。図書館は自分で誘導しよう

 

おすすめ

転載: blog.csdn.net/weixin_63676550/article/details/130183623