[問題] 請問字典功能
想請問一個有關dictionary的問題:
我有一份text 檔案,裡面含有多筆的email address(有些有重複相同的),
現在如果我想利用此份text file一次建立一個字典
而不是一個一個address輸入
並計算相同address出現的次數
請問該如何寫比較好
我的想法是每筆email看成一個key
我嘗試這樣寫:
import string
for line in infile:
words= string.split (line)
if len(words)>=2 and words[0]=="From":
sec=words[1]
#construct a new dictionary
d={}
#add one to the count if the email address existed
d[sec]=d.get(sec,0)+1
#prints out the dictionary contents
for key,values in d.items():
print key,values
但最後會出現
wpokf@pfok 1
sadoifj@dijf 1
sadoifj@dijf 1
wpokf@pfok 1
sadoifj@dijf 1
也就是他無法累加次數
不曉得是哪裡出了問題了.請高手幫忙解答
已經困了三天>.<
謝謝各位囉
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 24.11.127.26
推
02/09 10:38, , 1F
02/09 10:38, 1F
討論串 (同標題文章)
Python 近期熱門文章
PTT數位生活區 即時熱門文章