Skip to content Skip to sidebar Skip to footer

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[

Solution 1:

Just add a list length check would solve the problem.

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

Solution 2:

You can also track the inappropriate line without affecting the flow/without error

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

Post a Comment for "I Am Getting An Index Error As List Out Of Range. I Have To Scan Through Many Lines"