2016-02-26 148 views
0

我是相當新的蟒蛇,我目前正試圖做一個練習,我似乎無法解決。蟒蛇字典 - 列表問題(2.7.XX)

基本上我有一個長文本(.txt)文件,其中包含電子郵件對話。現在從我必須通過文件讀取和列出所有的電子郵件地址(這是我能夠找到的)

name = raw_input("Enter file:") 
if len(name) < 1 : name = "file.txt" 
handle = open(name) 
for line in handle: 
    email = line.strip() 
if email.startswith('From: '): 
    name = email.split() 
    print name 

從這個輸出是2份行多行列表。

['From:', '[email protected]'] 
['From:', '[email protected]'] 
['From:', '[email protected]'] 
['From:', '[email protected]'] 
['From:', '[email protected]'] 

現在,我的問題是,我必須把剛纔這些電子郵件地址轉換成字典,並有旁邊的計數,如

[email protected] 5 

所以,現在我已經加入了循環到與獲得()函數

name = raw_input("Enter file:") 
if len(name) < 1 : name = "file.txt" 
handle = open(name) 
for line in handle: 
    email = line.strip() 
if email.startswith('From: '): 
    name = email.split() 
    print name 
for names in name: 
    count[names] = count.get(names,0) + 1 
    print count 

代碼在這一點上,我得到的完整列表及以下的輸出:

{'From:': 1} 
{'From:': 1, '[email protected]': 1} 

我現在怎麼才能在字典中找到[email protected]?似乎我無法將完整列表放入字典中,並且添加了我不需要的「發件人」。然後,我會嘗試寫剩下的字來打印字典中最大的數字,然後將其作爲我想要的輸出。

我一直堅持這一段時間,我需要不幸保持它簡單,加上減去我用過的功能。我試圖環顧互聯網和這裏,但我沒有嘗試過,迄今爲止,幫助我。我很新,所以我很抱歉,如果修復很明顯

在此先感謝。

回答

0
lst = (['From:', '[email protected]'], 
['From:', '[email protected]'], 
['From:', '[email protected]'], 
['From:', '[email protected]'], 
['From:', '[email protected]'] 
) 

emails = {} 
for i in lst: 
    email = i[1] 
    if email in emails.keys(): 
     emails[email] += 1 
    else: 
     emails[email] = 1 
print emails 

>>> {'[email protected]': 5} 

添加您發現郵件到列表,然後迭代它,或者你可以在一個單一的通

name = raw_input("Enter file:") 
if len(name) < 1 : name = "file.txt" 
handle = open(name) 

emails = {} 
for line in handle: 
    email = line.strip() 
    if email.startswith('From: '): 
     name = email.split() 
     if name[1] in emails.keys(): 
      emails[name[1]] += 1 
     else: 
      emails[name[1]] = 1 

print emails 
+0

不幸的是,不幫我,我需要從我的「名」變量(信息檢索的信息你把它當作第一個) –

+0

@ShaunSmit查看編輯 – PYPL

0

下面是使用列表理解更簡潔的解決方案做到這一點。

lst = (['From:', '[email protected]'], 
['From:', '[email protected]'], 
['From:', '[email protected]'], 
['From:', '[email protected]'], 
['From:', '[email protected]'], 
['From:', '[email protected]'], 
['From:', '[email protected]'], 
['From:', '[email protected]'], 
['From:', '[email protected]'], 
['From:', '[email protected]'], 
['From:', '[email protected]'], 
['From:', '[email protected]'], 
['From:', '[email protected]'], 
) 

unique_set = set([x[1] for x in lst]) 

emails = {} 
for i in unique_set: 
    emails[i] = len([x for x in lst if x[1] == i]) 

print emails 

在上面的代碼中,我第一次在你的列表創建唯一條目集通過檢查你的電子郵件元組即第二項X [1]。一個python 爲你做這個。獲得此集合後,我將過濾輸入列表並使用結果列表中的len方法計算原始列表中的條目數。我希望這是有幫助的。

0

open()返回一個文件對象,並且通常使用兩個參數:open(filename,mode)。

f = open('filename', 'r')#In your case you are reading from the file. 

    for line in f: 
      print line, 

你可以設置你所有的條件,開始從「從:」讀循環之前