提示:
Write a program that categorizes each mail message by which day of the week the commit was done. To do this look for lines that start with "from", then look for the third word and keep a runnning count of each of the days of the week. At the end of the program print out the contents of your dictionary (order does not matter).
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]
?你知道吗
我怎样才能避免这种情况?你知道吗
你的程序在线路上崩溃了
它出现在后面(第38行),而不是文件的第一行。你知道吗
在尝试从中获取day字段之前,请检查以确保
sline
有足够的元素。你知道吗查看链接的文件,我认为需要将
line.startswith('From')
更改为line.startswith('From ')
(注意后面的空格)。正在匹配From: ...
标题行(并且只有2个单词),而我认为您只需要包含更多信息的From ...
行。你知道吗用于文件文件.txt你知道吗
您的程序输出
这是因为第二行没有第三个词。您需要在程序中实现错误控制。你知道吗
相关问题 更多 >
编程相关推荐