2014-12-03 26 views
0

的,我必須一個文本文件轉換成用逗號分隔的字符串列表(沒有空格,沒有第一行)。打印在此之後,我需要打印每一個國家的名字,多少行包含每個狀態,所有Cen2010值的每個狀態的總和(每行第1號),Est2013值(每行的最後一個數字的總和)以及每個州從Cen2010人口到Est2013人口的總變化。Jython的轉換文本文件中列出的字符串

文本文件示例:

名稱,STNAME,Cen2010,Base2010,Est2010,Est2011,Est2012,Est2013
「阿賓登城市」,伊利諾伊州,3319,3286,3286,3270,3242,3227
「Addieville村」,伊利諾伊州,252,252,252,250,250,247
「艾迪生村」,伊利諾伊州,36942,36964,37007,37181,37267,37385
「艾德琳之鄉」,伊利諾伊州,85,85,85,84,84,83

目前代碼:

def readPopest(): 
    censusfile=pickAFile() 
    cf=open(censusfile,"rt") 
    cflines=cf.readlines() 
    for i in range(len(cflines)-1): 
    lines=cflines[i+1] 
    estimate=lines.strip().split(',') 
    print estimate 

返回:
[ ' 「阿賓登城」', '伊利諾伊州', '3319', '3286', '3286', '3270', '3242',「3227 ']
['Addieville village'','Illinois','252','252','252','250','250','247']
[''Addison village'', '伊利諾伊', '36942', '36964', '37007', '37181', '37267', '37385']
[ ' 「愛德玲村」', '伊利諾伊', '85', '85', '85', '84', '84', '83']

回答

0

我想你可以導入這個數據到SQL數據庫和那麼它是很容易總結,過濾等

但是在Python中,我們有字典。您可以讀取數據並填寫字典,其中鍵名是狀態的名稱。然後,對於每條線路,您都會將城鎮添加到此州的城鎮列表中,並將數字添加到已保存的數字中。當然,對於州內第一個城鎮,您必須創建兩個陣列的結構。一個是城鎮,一個是數字。在代碼中,它看起來像:

def add_items(main_dict, state, town, numbers): 
    try: 
     towns_arr, numbers_arr = main_dict[state] 
     towns_arr.append(town) 
     for i in range(len(numbers)): 
      numbers_arr[i] += numbers[i] 
    except KeyError: 
     town_arr = [town, ] 
     main_dict[state] = [town_arr, numbers] 

現在,你必須使用它在你的主代碼讀取文件:

state_dict = {} 
    cf = open(censusfile, "rt") 
    lines = cf.readlines() 
    for line in lines[1:]: # we skip 1st line 
     arr = line.strip().split(',') 
     town = arr[0] 
     state = arr[1] 
     numbers = [int(x) for x in arr[2:]] 
     add_items(state_dict, state, town, numbers) 
    print(state_dict) 

作爲功課嘗試打印這本詞典中所需的格式。

+0

這工作得很好,謝謝 – Jake 2014-12-06 22:43:34

相關問題