我編寫了一個簡單的程序來導入CSV邊界列表,計算指標,然後我想將每個節點的指標寫入CSV文件。計算指標很簡單,但正確編寫CSV是我遇到麻煩的地方。通過我現在正在做的方式,CSV結果最終將每個值用逗號分隔,並用「,」分隔列 - 下面的示例,其中第一列是節點ID,其他列是該節點的結果id:csv.writer和每個由逗號分隔的值,用「,」分隔的列 - 我錯過了什麼?
7,6,1,8,5,9「,」,0,。,1,0,2,4,5,9,「,」,0,。,0, 0,0,0,4,5「,」,「,0,......,5,0,8,9,4,7」,「,0,0,0,8,8,3, 1
4,6,9,7,7,3「」「」「」「」「」「」「」「」「」「」「」1,4,3,4,4,3「」0,0 ... 0,0 ,0,0,9,0,「,」,0,...,5,2,7,2,4,2,「,」,0,...,0,1,1,2,9,1
代碼
import sys
import networkx as nx
import csv
# load CSV edgelist into NetworkX
G = nx.read_edgelist(sys.argv[1], delimiter=',')
# calculate centrality metrics
degree = nx.degree_centrality(G)
between = nx.betweenness_centrality(G)
close = nx.closeness_centrality(G)
eigen = nx.eigenvector_centrality(G)
# write centrality results to a list
centrality = []
for i in G:
centrality.append("%s, %f, %f, %f, %f"%(i, degree[i], between[i], close[i], eigen[i]))
# write list to CSV
outfile = sys.argv[1].replace('.csv', 'metrics.csv')
with open(outfile, 'wb') as f:
csv.writer(f).writerows(centrality)