直接上代码:
import networkx as nx
G = nx.Graph()
path = './node_node_weight.txt'
word_list = []
with open(path,'r') as f:
for line in f:
cols = line.strip().split('\t')
G.add_nodes_from([cols[0],cols[1]])
G.add_weighted_edges_from([(cols[0], cols[1], float(cols[2]))])
word_list.append(cols[0])
#G.add_weighted_edges_from([(cols[1], cols[0], float(cols[2]))])
word_list.append(cols[1])
nx.write_adjlist(G,'G.adjlist')
node_node_weight.txt 中的数据格式如下:(是连接的节点对,有权无权都可以)
1022055 902435 1
902435 773623 1
773623 681831 1
681831 603438 1
603438 1545447 1
1545447 1358790 1
1358790 1045344 1
1045344 927084 1
927084 814036 1
814036 702701 1
702701 620846 1
620846 464938 1
464938 294616 1
294616 131397 1
131397 66306 1
66306 100710 1
得到的 G.adjlist 如下:
1022055 902435
902435 773623
773623 681831
681831 603438
603438 1545447
1545447 1358790
1358790 1045344
1045344 927084
927084 814036
814036 702701
702701 620846
620846 464938
464938 294616
294616 131397
131397 66306
66306 100710
By the way, 生成 edgelist 同理,
nx.write_edgelist(G,'G.edgelist')