我收到索引错误,因为列表超出范围。我必须扫描很多行

I am getting an Index error as list out of range. I have to scan through many lines

import nltk
import random
from nltk.tokenize import sent_tokenize, word_tokenize


file = open("sms.txt", "r")
for line in file:
    #print line
    a=word_tokenize(line)
    if a[5] == 'SBI' and a[6]== 'Debit':
        print a[13]

谁能帮我改正错误。该程序运行几行然后停止并给出索引超出范围错误。我了解该错误,但我不知道如何解决。我想基本上删除不可读的行。

只需添加一个 list length 检查即可解决问题。

if len(a) >= 14 and a[5] == 'SBI' and a[6]== 'Debit':
    print a[13]

您还可以在不影响 flow/without 错误的情况下跟踪不当行

    file = open("sms.txt", "r")
    for line_no,line in enumerate(file):
        a=word_tokenize(line)
        try:
            if a[5] == 'SBI' and a[6]== 'Debit':
                print a[13]
        except IndexError:
            print str(line_no)+" line doesn't have expected data"
            continue