2 回答

TA貢獻1860條經驗 獲得超9個贊
我有類似的答案給你。你也可以試試這個。您不需要計數器和退出語句。您可以將 while 語句本身定義為看門人。
我做了一些更多的改進。雖然這不會給你一個完美的聊天機器人,但它更接近了。
question = []
answer = []
q = input("Ask me anything: ")
while q.lower() != 'stop':
? ? i = -1
? ? z = q.lower().split()
? ? z.sort()
? ? for x in question:
? ? ? ? y = x.split()
? ? ? ? y.sort()
? ? ? ? if all(elem in y for elem in z):
? ? ? ? ? ? i = question.index(x)
? ? if i >= 0:
? ? ? ? print(answer[i])
? ? else:
? ? ? ? question.append(q.lower())
? ? ? ? a = input("How should i answer that? ")
? ? ? ? answer.append(a)
? ? q = input("Ask me anything: ")
輸出:
Ask me anything: What is your Name
How should i answer that? Joe
Ask me anything: What your name
Joe
Ask me anything: name
Joe
Ask me anything: your name
Joe
Ask me anything: what name
Joe
Ask me anything: what is name
Joe
如您所見,當您詢問“姓名是什么”時,它仍然假定您是在詢問您的姓名。您需要使用它來獲得更復雜的機器人。希望這可以幫助您朝著正確的方向前進。
我之前的回答也貼在這里。由于我們將字符串與列表進行比較,因此它必須完全匹配。檢查有問題的 q 并不能真正給你帶來優勢。您將需要拆分單詞并進行比較。這就是我在新回復中所做的(見上文)
question = []
answer = []
q = input("Ask me anything: ")
while q.lower() != 'stop':
? ? if q.lower() in question:
? ? ? ? i = question.index(q.lower())
? ? ? ? print (answer[i])
? ? else:
? ? ? ? question.append(q.lower())
? ? ? ? a = input("How should i answer that? ")
? ? ? ? answer.append(a)
? ? q = input("Ask me anything: ")

TA貢獻1830條經驗 獲得超9個贊
使模糊查找器通過替換為此if q == question[i]不if q in question[i]查找特定單詞但查找關鍵字來執行此操作
question = []
answer = []
qcount = 0
stop = 0
b = 0
while stop == 0:
b = 0
q = input("Ask me anything: ")
if q == "stop":
exit()
for i in range(qcount):
if q in question[i]: # HERE IS THE ANSWER
b = 1
print(answer[i])
if b == 0:
question.append(q)
qcount = qcount + 1
a = input("How should i answer that? ")
answer.append(a)
添加回答
舉報