2 回答
TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超9個(gè)贊
我有類似的答案給你。你也可以試試這個(gè)。您不需要計(jì)數(shù)器和退出語(yǔ)句。您可以將 while 語(yǔ)句本身定義為看門人。
我做了一些更多的改進(jìn)。雖然這不會(huì)給你一個(gè)完美的聊天機(jī)器人,但它更接近了。
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
如您所見,當(dāng)您詢問“姓名是什么”時(shí),它仍然假定您是在詢問您的姓名。您需要使用它來(lái)獲得更復(fù)雜的機(jī)器人。希望這可以幫助您朝著正確的方向前進(jìn)。
我之前的回答也貼在這里。由于我們將字符串與列表進(jìn)行比較,因此它必須完全匹配。檢查有問題的 q 并不能真正給你帶來(lái)優(yōu)勢(shì)。您將需要拆分單詞并進(jìn)行比較。這就是我在新回復(fù)中所做的(見上文)
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貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個(gè)贊
使模糊查找器通過替換為此if q == question[i]不if q in question[i]查找特定單詞但查找關(guān)鍵字來(lái)執(zhí)行此操作
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)
添加回答
舉報(bào)
