python-2.7 - 如何使用networkx从文本文件创建图形?

标签 python-2.7 networkx

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

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)

它给出了一个错误。有人可以帮助我如何构建图来计算每个节点的权重和度数吗?

最佳答案

您要做的第一件事是注释文件中的所有描述性数据。默认情况下,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

关于python-2.7 - 如何使用networkx从文本文件创建图形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43561944/

相关文章:

python-2.7 - PANDAS:写入 Excel 时更改为 1904 日期系统

python - 在循环中捕获异常回溯,然后在脚本末尾引发错误

Python - Networkx 搜索前驱节点 - 超出最大深度

python - 如何在图中隔离这些(包括图像)路径?

python - 如果图中的边不在预选列表中,如何迭代它们

python - 处理 Python ArgumentParser 中的错误

python-3.x - Python 文档 : Line by line reading of Word document

python - 使用pyaudio时什么是 block 、样本和帧

python - 在加权网络中查找 "percolation"阈值的算法

python - 如何绘制图形聚类系数的分布