I get an index error as a list is out of range. I need to scan across 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] 

Can someone help me fix the error. The program starts for several lines, then stops and gives an index error outside the range. I understand the error, but I do not know how to fix it. I want to basically delete lines that are not readable.

-1
source share
2 answers

Just add a list length check to solve the problem.

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

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

  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 
0
source

All Articles