我正在从Python2.7迁移到Python3,split出现了问题

2024-04-18 07:57:29 发布

您现在位置:Python中文网/ 问答频道 /正文

提示:

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]?你知道吗

我怎样才能避免这种情况?你知道吗


Tags: oftheinfromforthatlinenot
3条回答

你的程序在线路上崩溃了

From: stephen.marquard@uct.ac.za

它出现在后面(第38行),而不是文件的第一行。你知道吗

在尝试从中获取day字段之前,请检查以确保sline有足够的元素。你知道吗

查看链接的文件,我认为需要将line.startswith('From')更改为line.startswith('From ')(注意后面的空格)。正在匹配From: ...标题行(并且只有2个单词),而我认为您只需要包含更多信息的From ...行。你知道吗

用于文件文件.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

这是因为第二行没有第三个词。您需要在程序中实现错误控制。你知道吗

相关问题 更多 >