2014-03-27 89 views
0

這裏是一個Excel文件,應該讀取並保存在多個字典中,其中1個是帶有列表的。其他2可以很好地工作,但是'列表'不會節省任何東西。下面是Excel文件的樣子:如何使用循環將Excel文件保存到字典中?

woof jpg js  gif css png 
0  0 45  0 11 6 
total_time ip_packets_num http_packets_num avg_http_size packet_num tcp_packets_num 
76.11243916 395    200    378   1217   395 
srcip   host      dstip   referer  server  
10.183.195.140 edigitalsurvey.com 108.160.162.38  http://static.bbci.co.uk.css   
       ichef.bbci.co.uk 212.58.244.69  http://static.bbci.co.uk.css   
       notify3.dropbox.com 46.236.9.36   http://static.bbci.co.uk.css   
       sa.bbc.co.uk  77.72.112.168  http://static.bbci.co.uk/.css   
       static.bbci.co.uk 81.23.53.170   http://static.bbci.co.uk.css   
       www.bbc.co.uk  81.23.53.171   http://static.bbci.co.uk.css   
                 http://www.bbc.co.uk/  

與列表中的字典是從5個線後記保存,它被初始化爲:

DAlllists={'scrip':[],'dstip':[],'host':[],'referer':[],'server':[]} 

,我使用的代碼是:

for caption in range(len(DAlllists)): 
if Dworksheet.cell_value(4,caption)=='srcip': 
    for row in range(len(DAlllists['srcip'])): 
     DAlllists['srcip'].append(Dworksheet.cell_value(5+row,caption)) 
if Dworksheet.cell_value(4,caption)=='dstip': 
    for row in range(len(DAlllists['dstip'])): 
     DAlllists['dstip'].append(Dworksheet.cell_value(5+row,caption)) 
if Dworksheet.cell_value(4,caption)=='host': 
    for row in range(len(DAlllists['host'])): 
     DAlllists['host'].append(Dworksheet.cell_value(5+row,caption)) 
if Dworksheet.cell_value(4,caption)=='referer': 
    for row in range(len(DAlllists['referer'])): 
     DAlllists['referer'].append(Dworksheet.cell_value(5+row,caption)) 
if Dworksheet.cell_value(4,caption)=='server': 
    for row in range(len(DAlllists['server'])): 
     DAlllists['server'].append(Dworksheet.cell_value(5+row,caption)) 

但輸出似乎沒有將任何內容保存到該字典中,只是在初始化時給出空白字典。 任何人有任何想法來改善代碼?

+0

LEN(DAlllists [「dstip」])是零,因此你的循環不會運行在所有。你可能應該循環,直到你得到空單元格。也許我會在稍後寫一個答案。 – x3al

回答

0

嘗試刪除所有的代碼,並使用此:

def read_xc_column(sheet, column, startrow=0): 
    row = startrow 
    value = sheet.cell_value(row, column) 
    answer = [] 
    while value: 
     answer.append(value) 
     row = row + 1 
     value = sheet.cell_value(row, column) 
    return answer 

DAlllists = {} 
for x in range(5): 
    this_col = read_xc_column(Dworksheet, x, 4) 
    DAlllists[this_col[0]] = this_col[1:] 
相關問題