2017-10-11 33 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. 

你應該考慮學習什麼字典,這會幫助你很多。