【问题标题】:how to create graph using networkx from text file?如何使用来自文本文件的 networkx 创建图形?
【发布时间】:2017-04-22 16:52:11
【问题描述】:

我有一个这样的文本文件:

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

我想使用 networkx 创建一个有向图,然后计算每个节点的度数和权重。

import networkx as net
import urllib
import csv
g = net.Graph()
f1 = csv.reader(open("graphdata.txt","rb"))
for x,y,z in f1: 
    g.add_nodes_from(x,y,z)

它给出了一个错误。谁能帮助我了解如何构建图表来计算每个节点的权重和度数?

【问题讨论】:

  • 你能描述一下它抛出的错误吗?

标签: python-2.7 networkx


【解决方案1】:

您要做的第一件事是注释文件中的任何描述性数据。默认情况下,Networkx 将任何以 # 开头的行视为注释。

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

我建议您阅读Reading and writing graphs in Networkx 并查看read_edgelist

【讨论】:

    猜你喜欢
    • 2016-01-30
    • 2017-04-27
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    相关资源
    最近更新 更多