我不知道为什么我保留了错误的答案。我首先在hand循环中找到了通过for line的天数,然后通过dictionary添加了键和值,但我没有得到我想要的输出。你能帮帮我吗?比你!
练习2:编写一个程序,按照提交的日期对每个邮件进行分类。为此寻找线开始"从",然后寻找第三个单词并保持运行数星期的每一天。在程序结束时打印出字典的内容(顺序无关)。
样本:
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
示例执行:python dow.py
Enter a file name: mbox-short.txt
{'Fri': 20, 'Thu': 6, 'Sat': 1}
我的代码
#mbox-short.txt
fname = input("Enter a file name: ")
hand = open(fname)
counts = dict()
for line in hand:
line = line.rstrip()
if not line.startswith('From '): continue
words = line.split()
words = words[2]
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
print(counts)
输出{'S': 1, 'a': 1, 't': 1, 'F': 20, 'r': 20, 'i': 20, 'T': 6, 'h': 6, 'u': 6}
您的代码中有一些逻辑错误,您可以尝试一下并与您的代码进行比较。(第2段放错了)
如果你有任何问题,请稍后再问。(假设数据文件仍然可用,这是很久以前完成的)dc_days = {} # Initializes the dictionary
file_name = input('Enter a file name: ')
try:
fp = open(file_name)
except FileNotFoundError:
print('File cannot be opened:', file_name)
exit()
for line in fp:
words = line.split()
if len(words) < 3 or words[0] != 'From':
continue
else:
if words[2] not in dc_days:
dc_days[words[2]] = 1 # seen first time
else:
dc_days[words[2]] += 1 # more to count
print(dc_days)