利用python求解节点介数和边介数
利用python求解节点介数和边介数
利用networkx里面的函数betweenness_centrality(G)来求解节点介数和函数edge_betweenness_centrality(G)来求解边介数
# -*- coding: utf-8 -*- """ Created on Sat Sep 14 18:01:27 2019 @author: Administrator """ import matplotlib.pyplot as plt import networkx as nx import operator def matrix_to_graph(): G = nx.Graph() filestr = "" #需要读入的邻接矩阵 with open("mlMatrix.txt") as files: for line in files: filestr += line.strip() #将字符串转换成列表 matrix = eval(filestr) nodes = range(len(matrix)) G.add_nodes_from(nodes) for i in range(len(matrix)): for j in range(len(matrix)): if(matrix[i][j] == 1): G.add_edge(i, j) bc= nx.centrality.betweenness_centrality(G,normalized=False) ebc = nx.centrality.edge_betweenness_centrality(G,normalized=False) print("节点编号及其节点介数最大值为:") bc_list = sorted(bc.items(), key=operator.itemgetter(1)) print(bc_list) print("-----------------------------------") print("节点编号及其边介数最大值为:") ebc_list = sorted(ebc.items(), key=operator.itemgetter(1)) print(ebc_list) matrix_to_graph()
节点介数
边介数