提示:
编写一个程序,根据提交完成的星期几对每封邮件进行分类。为此,请查找以“from”开头的行,然后查找第三个单词并记录一周中每一天的运行计数。在程序结束时打印出字典的内容(顺序无关紧要)。
Python 3 中的代码:
fname = input('enter file name:')
fhand = None
days = dict()
try:
fhand = open(fname)
except:
print(fname, 'is not a file thank you have a nice day and stop trying to ruin my program\n')
exit()
for line in fhand:
sline = line.split()
if line.startswith('From'):
print (sline)
day = sline[2]
if day not in days:
days[day] = 1
else:
days[day] += 1
print(days)
问题:
['From', 'stephen.marquard@uct.ac.za', 'Sat', 'Jan', '5', '09:14:16', '2008']
**['From:', 'stephen.marquard@uct.ac.za']**
Traceback (most recent call last):
File "C:\Users\s_kestlert\Desktop\Programming\python\chap9.py", line 13, in <module>
day = sline[2]
IndexError: list index out of range
文件: http: //www.py4inf.com/code/mbox-short.txt
为什么.split
将线切割成只有[0]
和[1]
?
我该如何规避这个?