how to create graph using networkx from text file?

后端 未结 1 1250
没有蜡笔的小新
没有蜡笔的小新 2021-01-21 17:30

// I have a text file include

node1  node2  weight
1      2      3
1      4      4
3      6      1
3      7      5
....
....

I want to creat

相关标签:
1条回答
  • 2021-01-21 18:18

    The first thing you have to do is to comment any descriptive data in your file. By default, Networkx considers any line starting with # as a comment.

    #node1 node2 weight

    1 2 3 ...

    import networkx as net
    FielName="GraphData.txt"
    Graphtype=net.DiGraph()   # use net.Graph() for undirected graph
    
    # How to read from a file. Note: if your egde weights are int, 
    # change float to int.
    G = net.read_edgelist(
        FielName, 
        create_using=Graphtype,
        nodetype=int,
        data=(('weight',float),)
    )
    
    # Find the total number of degree, in_degree and out_degree for each node
    for x in G.nodes():
        print(
            "Node: ", x, " has total #degree: ",G.degree(x),
            " , In_degree: ", G.out_degree(x),
            " and out_degree: ", G.in_degree(x)
        )
    
    # Find the weight for each node
    for u,v in G.edges():
          print ("Weight of Edge ("+str(u)+","+str(v)+")", G.get_edge_data(u,v))
    

    I recommend you to read the Reading and writing graphs in Networkx and have a look to read_edgelist

    0 讨论(0)
提交回复
热议问题