Python usa redes para leer archivos txt y dibujar un gráfico dirigido

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

El formato del archivo txt es el siguiente: los pesos de los puntos inicial y final están separados por espacios. En cuanto a la biblioteca, guiémosla por nosotros mismos.

 

Supongo que te gusta

Origin blog.csdn.net/weixin_63676550/article/details/130183623
Recomendado
Clasificación