我收到“ INDEXERROR:列表索引超出范围”的问题。
对于我编写的类似代码,不会发生这种情况。
我用-------符号-------指示错误行。
。。。。。。。
#import json
result = {}
#declare variables
count = -1
category = None
paragraph = None
#list of files
file_lists = ["sc.txt" ]
for file in file_lists:
#read line
for line in open(file,'r').readlines():
pieces = line.split('\t')
#if category is empty assign 'category' from line 1
if (category == None):
category = pieces[0]
#if starts with 'Question' skip
elif (pieces[0].startswith('Question')):
continue
#if------ ERROR OCCURS RIGHT BELOW THIS LINE !!!!!------------
elif ((pieces[0] != '') and (pieces[1] == '')):
paragraph = pieces[0]
#add incorrect to the dict
elif ((pieces[0] != '') and (pieces[1] != '')):
count += 1
result[count] = {'Category': category,
'Question': paragraph,
'Given_sen': pieces[0],
'Incorrect':[pieces[1]],
'Correct': pieces[2],
'Rule': pieces[3]
}
elif (pieces[0].startswith('')):
result[count]['Incorrect'].append(pieces[1])
您可以将try除外添加到代码中,如下所示,并跟踪哪一行破坏了代码
for line in open(file,'r').readlines():
try:
pieces = line.split('\t')
...
except IndexError as ie:
print ie
或者,如果您所有的行始终被分割为相同长度的元素。您可以检查len(pieces)
如果长度不等于期望的长度值,请使用continue
忽略其余代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句