2017-04-04 111 views
-1

我創建了一個學習機器人,創建一個文件到數據庫,但插入錯誤,可以幫助我嗎?蟒蛇 - 插入錯誤

代碼:

#kernel now ready for use 
while True: 
if mode == "voice": 
    response = listen() 
else: 
    response = raw_input("Say: ") 
    if response == "aprender": 
     learn = raw_input("Learn: ") 
     f = open("database.aiml", "r") 
     contents = f.readlines() 
     f.close() 

     #ERROR HERE>> contents.insert("1", "<category>\n<pattern>*</pattern>\n<template>\n", learn, "</template>\n</category>\n") 

     f = open("database.aiml", "w") 
     contents = "".join(contents) 
     f.write(contents) 
     f.close() 
+2

什麼是錯誤您收到? – umutto

+0

Python的關閉,當我嘗試使用學習:contents.insert( 「1」, 「 \ n * \ n \ n \ n」) –

+0

請(重新)閱讀「[問]」,然後[編輯]你的問題提供[mcve],包括錯誤消息和整個堆棧跟蹤(假設有一個)。 –

回答

0

什麼是你想在這裏究竟做什麼?內容是一個列表對象,所以插入應該有兩個參數:一個索引和你想插入的東西(在你的情況下是一個字符串)。

我會先嚐試改變,爲以下內容,請參閱影響是什麼:

contents.insert(1, "<category>\n<pattern>*</pattern>\n<template>\n" + learn \ 
+ "</template>\n</category>\n") 
+0

是的,這工作,但我想做的字符串和變量的交界處,我可以這樣做嗎? –

+1

你是什麼意思的字符串和變量的交界處?如果你的意思是串聯,那麼你可以通過使用+符號(我已經更新了我的答案來反映) –

+0

哇,這個工程!非常感謝,阿比德! –