【发布时间】:2016-08-08 10:10:13
【问题描述】:
我正在做 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"
name="mbox-short.txt"
handle=open(name)
text=handle.read()
for line in handle:
line=line.rstrip()
words=line.split()
if words==[]: continue
if words[0]!='From':continue
words2=words[1]
words3=words2.split()
counts=dict()
for word in words3:
counts[word]=counts.get(word,0)+1
bigcount=None
bigword=None
for key,val in counts.items():
if val>bigcount:
bigword=key
bigcount=val
print bigword,bigcount
我的输出是: cwen@iupui.edu 1
我的代码中的错误在哪里?
【问题讨论】:
-
不知道。怎么了?
-
尝试使用
for line in text而不是for line in handle -
我的输出应该是 cwen@iupui.edu 5。但它即将到来 cwen@iupui.edu 1
-
@dhdavvie 我试过了,但它不起作用
-
除了
words2上的NameError,我看不到它是如何产生任何东西的,因为handle应该是空的,因为已经完成了handle.read(),然后只定义了words2for line in handle循环,因为文件对象的指针在末尾,所以该循环中的任何内容都不会执行。
标签: python python-2.7 python-3.x dictionary