簡體   English   中英

使用 dict 嵌套 for 循環

[英]Nested for loop using dict

我正在做 Coursera python 練習並且在編寫代碼時遇到問題。

問題如下:

編寫一個程序來讀取mbox-short.txt並找出誰發送了最多的郵件消息。 該程序查找“發件人”行並將這些行的第二個單詞作為發送郵件的人。

該程序創建了一個 Python 字典,該字典將發件人的郵件地址映射到它們在文件中出現的次數的計數。 生成字典后,程序使用最大循環讀取字典以查找最多產的提交者。

示例文本文件在這一行: http : //www.pythonlearn.com/code/mbox-short.txt

預期的輸出應該是:

cwen@iupui.edu 5

這是我的代碼:

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
count = dict()

for line in handle:
    word = line.split()
    if line.startswith('From '):
        email = word[1]
        for sender in email:
            if sender not in count:
                count[sender] = count.get(sender, 0) + 1

bigcount = None
bigname = None
for name,count in count.items():
    if bigname is None or count > bigcount:
        bigname = name
        bigcount = count
print bigname, bigcount

我的輸出是:

. 1

我認為“對於電子郵件中的發件人”部分有問題,但無法弄清楚它是如何導致不需要的輸出的。

在這種情況下,以下循環不合適,因為您基本上是在遍歷電子郵件地址的所有字符。

for sender in email:
   ...

這就是為什么你會得到一個角色. 當您打印計數最大的電子郵件地址時。 在循環結束時打印計數后,您可以輕松查看效果。

以下檢查也是多余的,因為當您使用get方法獲取字典值時,您正在隱式檢查它。

if sender not in count:
   ...

所以,最終更正后的代碼應該是這樣的。

name = raw_input("Enter file:")
if len(name) < 1:
    name = "mbox-short.txt"
handle = open(name)
count = dict()

for line in handle:
    word = line.split()
    if line.startswith('From '):
        count[word[1]] = count.get(word[1], 0) + 1
largest = 0
email = ''
for k in count:
    if count[k] > largest:
        largest = count[k]
        email = k
print largest, email
fname = input("Enter The File Name")
fhandle = open(fname,'r')

sender = dict()
for line in fhandle:
    if line.startswith("From "):
        sender[line.split()[1]] = sender.get(line.split()[1],0) + 1

max_key = None
max_val = None

for key,value in sender.items():
    if max_val is None or max_val < value :
        max_val = value
        max_key = key

print(max_key,max_val)
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
words = list()
counts = dict()

for line in handle:
    words = line.split()
    if words == []: continue
    if words[0] != 'From': continue
    counts[words[1]] = counts.get(words[1],0) + 1
    #print counts


maxval = None
maxkey = None

for kee, val in counts.items():
    if maxval == None: maxval = val
    if maxval < val: 
        maxval = val
        maxkey = kee
print maxkey, maxval
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
fl = open(name)

#fl=open('C:\Users\Algoritm\Documents\Python Coursera\mbox-short.txt')
lst=list()
count=dict()

#scan the file and create a list
for lines_in_the_file in fl:
xx=lines_in_the_file.rstrip().split()
if not lines_in_the_file.startswith('From '): continue #if in the line keep it
word=lines_in_the_file.split()
#print word[1]
xx=word[1]
#for index in xx: #find repeted words in the list Word
lst.append(xx)

#print lst
lis=lst
for x in lis:
count[x]=count.get(x,0)+1

#print  count
bigcount=None
bigwords=None



for x, y in count.items():
if bigcount is None or y>bigcount:
   bigwords=x
   bigcount=y
print bigwords, bigcount
name = input("Enter the file name:")
handle = open(name)
new = dict()
#count = 0
for line in handle:
 word = line.split()
 if line.startswith("From "):
    new[word[1]] = new.get(word[1],0) + 1
largest = 0
email = None
for k,v in new.items():
 if email is None or v > largest:
    largest = v
    email = k
print (email,largest)
fname=input('enter the file name: ')
d=dict()
try:
    fhand=open(fname,'r')
except:
    print('file not found')
    exit()

for line in fhand: 

    if line.startswith("From:"):
        srt=line.find(' ')
        sl=line[srt:-1]

        if sl not in d:
            d[sl]=1
        else:
            d[sl]+=1

print(d)
largest= 0
email=''

for key in d:
    if d[key] > largest:
        largest=d[key]
        email=key
print(email,': ',largest)
我正在學習相同的 Coursera Python 課程。 由於我是新手,我正在分享我的作業代碼。 對我來說,關鍵部分是首先使用 if not line,然后拆分它。

 counts=dict() fname=input('Enter file: ') if len(fname)<1: fname='mbox-short.txt' else: print('Error') quit() fhand=open(fname) for line in fhand: if not line.startswith('From '): continue words=line.split() counts[words[1]]=counts.get(words[1],0)+1 key=None num=0 for k,v in counts.items(): if key is None or v > num: num=v key=k print (num, key)

name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
name = "mbox-short.txt"
handle = open(name)
text = handle.read()
#words = text.split()

words = list()

for line in handle:
    if not line.startswith("From:") : continue
    line = line.split()
    words.append(line[1])


counts = dict()

for word in words:
           counts[word] = counts.get(word, 0) + 1 


maxval = None
maxkey = None
for key,val in counts.items() :
#   if maxval == None : maxval = val
  if val > maxval:
      maxval = val
      maxkey = key   

print (maxkey, maxval)
counts = dict()
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
fhand = open(name)
for line in fhand:
       line = line.rstrip()
       if not line.startswith('From ') : continue
       words = line.split()            
       counts[words[1]]=counts.get(words[1],0)+1 
st = 0 
for k in counts:
       if counts[k] > st :
       st = counts[k]
       addy = k
print (addy, st)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM