概述
吐槽:还是没听课,然后被数据和系统坑了好久= =
9.4 Write a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file. After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer.
You can download the sample data at https://www.py4e.com/code3/mbox-short.txt
文件太长了,点上面链接看吧= =
我的程序:
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name) #到此为止都是题目给的一部分代码
dic = dict()
maxvalue = 0
maxkey = ''
content = ''
for line in handle:
if(line.startswith("From: ")):
lst = line.rstrip().split(' ')
dic.update({lst[1]:0})
content += line.rstrip()
for key in dic.keys():
dic[key] = content.count(key)
if(dic[key] > maxvalue):
maxvalue = dic[key]
maxkey = key
print(maxkey + ' ' + str(maxvalue))
输出:
cwen@iupui.edu 5
我想说的:
1,这个题坑在里面有句话叫 a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file ,但是答案给出的不是文件中出现的总次数,认真读题发现是求发送邮件最多的人和次数,所以要小心 content 并不是 handle.read() 。
2,题目上说是From开头的,我把 line.startswith("From") 替换上去则会发现答案是10,不是5,所以很坑哦,仔细看一下文件发现改成 line.startswith("From: ") 就过了。
3,因为需要提交到他的oj,然而里面并没有实现 dict.fromkeys(seq) 的功能(https://www.runoob.com/python/att-dictionary-fromkeys.html),所以无奈只能用 dict1.update(dict2) 来实现(https://www.runoob.com/python/att-dictionary-update.html)。
4,str.count(sub) 真是个好东西(https://www.runoob.com/python/att-string-count.html)。
5,Python中的字符串连接不会像Java一样自动调用toString(),所以要写成str(xxx),注意报错信息就能改对了,只是提个醒咯。
最后
以上就是高高冬天为你收集整理的【题解】Assignment 9.4 (Python Data Structures)的全部内容,希望文章能够帮你解决【题解】Assignment 9.4 (Python Data Structures)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复