我编写了一个简单的程序来导入CSV边缘列表,计算指标,然后我想将每个节点的指标写入CSV文件。计算指标很简单,但正确编写CSV是我遇到麻烦的地方。通过我现在这样做的方式,CSV结果最终将每个值用逗号分隔,并且列以","分隔。 - 下面的示例,其中第一列是节点标识,其他列是该节点标识的结果:
7,6,1,8,5,9,",",0,。,1,0,2,4,5,9,",&#34 ;,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,",",0,。,1,4,3,4,4,3,",&#34 ;,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)
答案 0 :(得分:2)
writerows
需要一个值列表列表,其中每个“外部”列表都是一行值。
但是,您传递的是字符串列表。 writerows
只迭代每个字符串的元素,因此每个字母都成为自己的列。当逗号为csv值时,需要引用逗号,因此将它们添加为","
。
删除字符串格式(csv
模块处理),只说:
centrality.append((i, degree[i], between[i], close[i], eigen[i]))
内括号表示tuple符号。你可以说得更清楚:
row = i, degree[i], between[i], close[i], eigen[i]
centrality.append(row)