我正在从 Python 2.7 移动到 Python 3 并且 .split 正在运行

I am moving from Python 2.7 to Python 3 and .split is acting up

提示:

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).

Python3中的代码:

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]

我该如何避免这种情况?

对于文件 file.txt

From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
From: stephen.marquard@uct.ac.za

你的程序输出

enter file name:file.txt
['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 "test.py", line 13, in <module>
    day=sline[2]
IndexError: list index out of range

这是因为第二行没有第三个字。你需要在你的程序中实现错误控制。

你的程序在线崩溃

From: stephen.marquard@uct.ac.za

稍后出现(第 38 行),而不是文件的第一行。

检查以确保 sline 有足够的元素,然后再尝试从中获取日期字段。

查看您链接的文件,我认为您需要将 line.startswith('From') 更改为 line.startswith('From ')(注意结尾的 space)。 From: ... header 行正在匹配(并且只有 2 个单词),而我认为您只想要包含更多信息的 From ... 行。