2017-10-11 57 views
1

我刚刚进入编码并有一个查询。 我正在写一个名为Sasha的聊天机器人的脚本,但是我无法找到任何方法来解决在一个句子中不匹配所有单词的问题。假设,我想要求它检查日期的不同,而不是仅仅说'日期'。我会怎么做呢? 任何帮助表示赞赏。如何在输入python中搜索和打印项目?

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

你可以使用字典映射输入回答

更新: 添加正则表达式来匹配输入,但我觉得你的问题更像是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 
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" 
1

你可以用“在”来检查,如果事情是在一个列表,如下所示:(伪代码)

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. 

你应该考虑学习什么字典,这会帮助你很多。