使用dict嵌套for循环

时间:2016-03-13 23:16:13

标签: python python-2.7 dictionary

我正在进行Coursera python练习并且无法编写代码。

问题如下:

  

编写一个程序来阅读mbox-short.txt并找出谁发送了最多的邮件消息。该计划寻找' From'行并将这些行的第二个单词作为发送邮件的人。

     

该程序创建一个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

我认为对于电子邮件中的发件人来说有什么问题&#34;部分,但无法弄清楚它是如何导致不良输出的。

9 个答案:

答案 0 :(得分:1)

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)

答案 1 :(得分:0)

在这种情况下,以下循环是不合适的,因为您基本上是在遍历电子邮件地址的所有字符。

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

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)

答案 5 :(得分:0)

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)

答案 6 :(得分:0)

我正在上同一门Coursera Python课程。由于我是新手,所以我要分享作业代码。对我来说,关键部分是首先使用(如果不是行的话),然后将其拆分。

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)

答案 7 :(得分:0)

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)

答案 8 :(得分:0)

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)