Nebulabauer
Nebulabauer

Reputation: 31

How to search for and print items in the input, python?

I just got into coding and have a query. I'm writing a script for a chatbot named Sasha, however I am not able to find any method to solve the problem of not all words matching in a sentence. Say, I want to ask it to check the date differently rather than just saying, 'date'. How would I go about doing that ? Any help is appreciated.

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])

Upvotes: 1

Views: 79

Answers (3)

galaxyan
galaxyan

Reputation: 6121

you could use dict to map input to answer

update: add regex to match the input, but I think your question more like NLP question.

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

output:

date
it is the 13th of October 2017

Upvotes: 0

Kurt Ferrier
Kurt Ferrier

Reputation: 73

You can use 'in' to check if something is in a list, like so: (in pseudocode)

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.

You should consider learning about what dictionaries are, that would help you a lot.

Upvotes: 1

Daniel Lee
Daniel Lee

Reputation: 8021

A very rudimental answer would be to check for a word in the sentence:

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"

Upvotes: 0

Related Questions