我得到一个索引错误,因为列表超出范围。我必须浏览许多行

2024-03-29 01:39:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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]

有谁能帮我纠正错误吗。程序运行了几行,然后停止运行,给出一个索引超出范围的错误。我理解这个错误,但我不知道如何改正它。我想基本上删除那些不可读的行。在


Tags: fromimporttxtfor错误linerandomopen
2条回答

您还可以跟踪不合适的行而不影响流程/无错误

    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

只要添加一个list length检查就可以解决问题。在

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

相关问题 更多 >