2014-06-25 48 views
0

我編寫了一個簡單的程序來導入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) 

回答

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)