2014-10-11 59 views
0

返回最流行的名字因此,這裏的文本文件,我的工作:讀取文本文件,併爲當年

AK,F,1910,Mary,14 
AK,F,1910,Annie,12 
AK,F,1910,Anna,10 
AK,F,1910,Margaret,8 
AK,F,1910,Helen,7 
AK,F,1910,Elsie,6 

文本文件包含每一個國家。它一直持續到21世紀。每年都會列出性別M和F,每年年初的第一個名字是最受歡迎的一年。例如,瑪麗在1910年最流行的嬰兒名字 我的代碼應該返回是這樣的:

Enter state: ny 
Enter gender: f 
Enter start year: 2004 
Enter end year: 2007 
Top female names for NY between 2004-2007: 
In 2004 Emily occurred the most at 1590 times 
In 2005 Emily occurred the most at 1444 times 
In 2006 Emily occurred the most at 1317 times 
In 2007 Isabella occurred the most at 1425 times 
Emily occurred consecutively the most in this range at 3 time/s 

我已經有很多這樣的程序寫的。我只需要一些關於如何返回代表 範圍內每年的頂級名稱的名稱對象列表的建議。

+0

所以代碼在哪裏,它的問題究竟是什麼?這不是一個代碼寫入服務。 – jonrsharpe 2014-10-11 17:43:57

+0

@亞當:如果它幫助你完成作業,請投我的答案。 – 2014-10-14 18:54:49

回答

-1

這裏是你如何能做到(這是2.7.8,我沒有這臺機器上3.X):

from collections import defaultdict, Counter 

data = '''-,-,1970,John,- 
-,-,1970,John,- 
-,-,1970,Paul,- 
-,-,2014,Bob,- 
-,-,2014,Mary,- 
-,-,2014,Mary,-''' 

temp = defaultdict(list) 

for record in (line.split(',') for line in data.splitlines()): 
    y = record[2] 
    n = record[3] 
    temp[y].append(n) 

results = [(k, Counter(v).most_common(1)) for k,v in temp.items()] 

[( '2014',[( '瑪麗', 2)]),( '1970',[( '約翰',2)])]

for year,r in results: 
    if int(year) in valid: 
    print('In {0} the name {1} occured the most ({2} times)'.format(year, r[0][0], r[0][1])) 

在2014名瑪麗發生最(2次)

在1970約翰發生的名稱最多(2次)

+0

如果您需要獲取每年的所有計數,請刪除.most_common,如果您需要每年的前3名,請使用.most_common(3) – 2014-10-11 18:10:24

+0

我的代碼有什麼問題? – 2014-10-12 07:11:39

相關問題