我刚进入编码并进行查询。 我正在为一个名为Sasha的聊天机器人编写脚本,但是我无法找到任何方法来解决句子中并非所有单词匹配的问题。 说,我想让它以不同的方式检查日期,而不仅仅是说,' date'。我该怎么做呢? 任何帮助表示赞赏。
Database =[
['hello sasha', 'hey there'],
['what is the date today', 'it is the 13th of October 2017'],
['name', 'my name is sasha'],
['weather', 'it is always sunny At Essex'],
]
while 1:
variable = input("> ")
for i in range(4):
if Database[i][0] == variable:
print (Database[i][1])
答案 0 :(得分:1)
您可以使用'in'来检查列表中是否有某些内容,如下所示:(在伪代码中)
list = ['the date is blah', 'the time is blah']
chat = input('What would you like to talk about')
if chat in ['date', 'what is the date', 'tell the date']:
print(list[0])
elif chat in ['time', 'tell the time']:
print(list[1])
etc.
您应该考虑了解哪些词典,这对您有很大的帮助。
答案 1 :(得分:0)
您可以使用dict将输入映射到答案
更新: 添加正则表达式以匹配输入,但我认为你的问题更像是NLP问题。
import re
Database ={
'hello sasha': 'hey there',
'what is the date today':'it is the 13th of October 2017',
'name': 'my name is sasha',
'weather': 'it is always sunny At Essex',
}
while 1:
variable = input("> ")
pattern= '(?:{})'.format(variable )
for question, answer in Database.iteritems():
if re.search(pattern, question):
print answer
输出:
date
it is the 13th of October 2017
答案 2 :(得分:0)
一个非常基本的答案是检查句子中的单词:
while 1:
variable = input("> ")
for i, word in enumerate(["hello", "date", "name", "weather"]):
if word in input.split(" "): # Gets all words from sentence
print(Database[i][1])
in: 'blah blah blah blah date blah'
out: 'it is the 13th of October 2017'
in: "name"
out: "my name is sasha"