2016-07-13 5 views
1

"INDEXERROR:リストインデックスが範囲外です"という問題が発生しています。インデックスエラーが発生しています...

私が書いた類似のコードでは発生しません。 すべてのアイデア??

私はエラー行を------- sign -------で示します。

。 。 。 。 。 。 。

#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]) 
+0

行の1つにタブがありません。 –

+0

あなたの行のほとんどはタブを含まない可能性があります – kdopen

答えて

0

あなたは以下のようにあなたのコードを除い試みを追加し、すべての行が常に要素の同じ長さに分割されている場合は、

for line in open(file,'r').readlines(): 
    try: 
     pieces = line.split('\t') 
     ... 

    except IndexError as ie: 
     print ie 

代わりにあなたのコードを壊した行を追跡することができます。 len(pieces)長さが予想される長さの値と等しくない場合は、continueを使用して残りのコードを無視してください。

関連する問題