2011-10-24 96 views
0

當我嘗試打印splited_data[1]我收到錯誤消息IndexError: list index out of range,另一方面splited_data[0]工作正常。 我想插入數據到MySQL中。 splited_data[0]是我的MySQL列,splited_data[1]是mysql的列值。我想如果splited_data[1]爲空,則在mysql中插入空字符串。但我得到IndexError: list index out of range。如何避免這個錯誤?請幫幫我。謝謝Python列表:IndexError:列表索引超出範圍

這是我的代碼。哪個工作正常。當splited_data[1]爲空時,我只會收到此錯誤消息。

def clean(data): 
     data = data.replace('[[','') 
     data = data.replace(']]','') 
     data = data.replace(']','') 
     data = data.replace('[','') 
     data = data.replace('|','') 
     data = data.replace("''",'') 
     data = data.replace("<br/>",',') 
     return data 


for t in xml.findall('//{http://www.mediawiki.org/xml/export-0.5/}text'): 
    m = re.search(r'(?ms).*?{{(Infobox film.*?)}}', t.text) 
    if m: 
     k = m.group(1) 
     k.encode('utf-8') 
     clean_data = clean(k) #Clean function is used to replace garbase data from text 
     filter_data = clean_data.splitlines(True) # splited data with lines 
     filter_data.pop(0) 
     for index,item in enumerate(filter_data): 
       splited_data = item.split(' = ',1) 
       print splited_data[0],splited_data[1] 

# splited_data[0] used as mysql column 
# splited_data[1] used as mysql values 

這裏是Splited_data數據

[u' music   ', u'Jatin Sharma\n'] 
[u' cinematography', u'\n'] 
[u' released  ', u'Film datedf=y201124'] 

回答

1
split_data = item.partition('=') 
# If there was an '=', then it is now in split_data[1], 
# and the pieces you want are split_data[0] and split_data[2]. 
# Otherwise, split_data[0] is the whole string, and 
# split_data[1] and split_data[2] are empty strings (''). 
+0

很容易使用。非常感謝。 :-) –

0

嘗試在等號的兩側刪除空格簽名,就像這樣:

splited_data = item.split('=',1) 
0

一個list是連續的。所以你需要確保它的長度大於你的索引,然後再嘗試訪問它。

'' if len(splited_data) < 2 else splited_data[1] 

你也可以查看你分割前:

if '=' in item: 
    col, val=item.split('=',1) 
else: 
    col, val=item, '' 
+0

感謝任何方式:-)。 'item.partition' –

相關問題