ex_08_05错误:list index out of range

// An highlighted block
'''
Open the file mbox-short.txt and read it line by line.
When you find a line that starts with 'From ' like the following line:
From stephen.[email protected].ac.za Sat Jan  5 09:14:16 2008
You will parse the From line using split() and print out the second word in the line
(i.e. the entire address of the person who sent the message).
Then print out a count at the end.
Hint: make sure not to include the lines that start with 'From:'.

You can download the sample data at http://www.py4e.com/code3/mbox-short.txt
将文件中以From开头的行,中的第二个字符串取出
'''

fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
count = 0
fh = open(fname)
words = list()
for line in fh:      #将文件一行一行读出
    words = line.split()  #用数组存储用空格分隔开的列表

    if len(words)<3 or words[0] != 'From':    #一定要加一句len(words)<3,用来保证数组不会操作,有些行没有三个字符串。
        # print(words)
        continue
    else:
        print(words[1])                     #打印第二个字符串
        count = count + 1

print("There were", count, "lines in the file with From as the first word")

在解析数据时,split是很好用的!先将文件分割成数组,在提取、解析其中的数据。

错误:list index out of range

ex_08_05错误:list index out of range