我正在为每个人做Coursera流,我被困在10.2作业中。我的输出是无效的。以下是任务要求:
编写一个程序来读取Mbox-短路. out,并按一天中每条消息的小时计算出分布。您可以从“from”行中提取时间,方法是找到时间,然后使用冒号再次拆分字符串。 2008年1月5日09:14:16从stephen.marquard@uct.ac.za Sat出发 一旦积累了每小时的计数,就打印出计数,按小时排序,如下所示。
这是我的代码:
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
lst = list()
for line in handle:
line = line.rstrip()
if not line.startswith('From '):
continue
words = line.split()
words = words[5]
words = words.split(":")
for word in counts:
counts[word] = counts.get(word, 0) + 1
lst = list()
for key, val in counts.items():
lst.append((key, val))
lst.sort()
print lst告诉我我做错了什么。如有任何建议或提示,我们将不胜感激。
发布于 2016-02-12 15:32:41
我认为您正在内部循环中迭代错误的东西:它应该是for word in words,而不是for word in counts。
发布于 2016-04-02 03:54:42
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
hours = dict()
for line in handle:
if line.startswith("From "):
hour = line.split()[5].split(':')[0]
hours[hour] = hours.get(hour, 0) + 1
for key, value in sorted(hours.items(), None):
print key, value发布于 2017-07-29 12:54:07
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = {}
for line in handle:
if not line.startswith("From "):continue
time = line.split()
time = time[5]
hour = time.split(':')
hour = hour[0]
counts[hour] = counts.get(hour, 0) + 1
for k, v in sorted(counts.items()):
print (k,v)https://stackoverflow.com/questions/35366313
复制相似问题