求解网络科学里面的接近中心性
import matplotlib.pyplot as plt
import networkx as nx
import operator
def get_closeness_centrality():
G = nx.Graph()
filestr = ""
#需要读入的邻接矩阵
with open("nsMatrix.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)
cc = nx.algorithms.bipartite.centrality.closeness_centrality(G,G.node())
print("节点编号及其接近中心性最大值为:")
cc_list = sorted(cc.items(), key=operator.itemgetter(1))
print(cc_list)
get_closeness_centrality()
邻接矩阵的格式如下:
[[1,1,1],[1,1,1],[1,1,1]]