如何使用networkx从文本文件创建图形? [英] how to create graph using networkx from text file?

查看:697
本文介绍了如何使用networkx从文本文件创建图形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//我有一个包含的文本文件

// I have a text file include

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

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

I want to create a directed graph using networkx then count the degree and weight for each node.

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)

它给出了一个错误.有人可以帮我建立图表来计算每个节点的权重和度吗?

It gives an error. Can anybody help me as to how build graph the compute the weight and degree for each node?

推荐答案

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

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.

1 2 3 ...

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

我建议您阅读在Networkx中读写图,并查看 read_edgelist

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

这篇关于如何使用networkx从文本文件创建图形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆