python - 我如何检查我的聊天机器人中的 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]
?
解决方案
Aryan Mishra 已经为您提供了答案。我有类似的答案给你。你也可以试试这个。您不需要计数器和退出语句。您可以将 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: ")
推荐阅读
- python - python tkinter Image - 创建一个新的而不是替换它
- mongodb - 如何在与猫鼬的接口中使用字符串文字类型?
- go - Goroutines 睡着了
- angular - 没有导出成员 'ɵɵFactoryDef'
- c# - C# WebService 使用 WebAPI 和 Entity for XML 教程?
- android - Android : 在 Java 中翻译 Kotlin ViewModel 支持字段封装技术
- python - pytest:如何暂时关闭互联网连接?
- html - 即使我有一些额外的空间,Flex-shrink 也不起作用
- c++ - 在 C++ 中的字符数组中输入空格分隔的输入
- php - Symfony:从 postgresql 获取时吃掉我所有的 ram