我如何检查我的聊天机器人中的 2 个句子是否相似

我使最简单的聊天机器人成为可能。它会根据您之前希望它回答同一问题的内容来回答您的问题。代码有点像这样:


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 == question[i]:

            b = 1

            print(answer[i])



    if b == 0:

        question.append(q)

        qcount = qcount + 1


        a = input("How should i answer that? ")

        answer.append(a)

有没有办法转


if q == question[i]


if q is similar to question[i]

?


慕妹3242003
浏览 103回答 2
2回答

慕码人2483693

我有类似的答案给你。你也可以试试这个。您不需要计数器和退出语句。您可以将 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 NameHow should i answer that? JoeAsk me anything: What your nameJoeAsk me anything: nameJoeAsk me anything: your nameJoeAsk me anything: what nameJoeAsk me anything: what is nameJoe如您所见,当您询问“姓名是什么”时,它仍然假定您是在询问您的姓名。您需要使用它来获得更复杂的机器人。希望这可以帮助您朝着正确的方向前进。我之前的回答也贴在这里。由于我们将字符串与列表进行比较,因此它必须完全匹配。检查有问题的 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: ")

慕标琳琳

使模糊查找器通过替换为此if q == question[i]不if q in question[i]查找特定单词但查找关键字来执行此操作question = []answer = []qcount = 0stop = 0b = 0while 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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python