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.marquard@uct.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

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值