Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Matching Exact String(s)
#1
Hello,

So I'm working on an A.I assistant and I got a good chunk of it done. It can display the news, weather, time, do calculations and google searches.

The problem that I am having right now, is that I want it to look for some exact strings when I say my command.

Here's what I mean:

For example, when I ask my A.I what the weather is, it will display today's weather (that's fine).
But If I ask it what the weather for the week is, it will display today's weather only.

I know it does this because since 'weather' is in the command it automatically jumps to the first weather statement (which will display today's weather).
This is the weather portion of the code:
 elif ('weather' in command):
        speak('Searching weather networks...')
        command = command.replace("weather","")
        #Call weather data  for today:
        displayWeatherData()

    elif ('weather for the week' in command):
        speak('Searching weather networks...')
        command = command.replace("weather for the week","")
        #Call weather data for the week:
        displayWeeksWeatherData()
What I want it to do is:
I want it to look for exact strings in my command. So if I say "What is the weather for the week" It will recognize that weather and week are used in the same sentence and it will jump to the "weather for the week" statement (therefore displaying the weather for the week).


I would also like to leave the "What is" part of the command open because that is part of the search statements so it know that I am asking a question that requires an internet search in order to be answered (For example: "What is the sun" or "What is pie")

But at the same time, if I say "What is the time?" I want the program to recognize that I am asking for the time and therefore it should jump to the time statement and display the current time. (So the program should basically ignore the 'what is' part and only look for the 'time' string when it's looking for the if statement that it has to match up with)
What it currently does:
If I say "Time" the program will display the current time
If I say "What is the time?" the program will give me the definition of time.
What it should do:
So If I say "What is the time" The program should display the current time
But if I say "What is the sun" The program will use an internet search to find an answer for "What is the sun" because sun is not explicitly defined in it's command list.

How would I go about doing this?

Thanks.


Here is the full code:
#!/usr/bin/env python3

import json
import random
import datetime
import operator
import os
import time
from time import process_time
import requests
from bs4 import BeautifulSoup
from Weather import *
import wikipedia
import wolframalpha
import pyttsx3
import espeakng
import speech_recognition as sr 

#-------------------------------------------------------------------------------------
                            #Commander Name (You) and A.I Name
#-------------------------------------------------------------------------------------
Commander = "Commander"
AI_Name = 'baxter'
#-------------------------------------------------------------------------------------

print ("Initializing B.A.X.T.E.R...")

def speak(text):
    mySpeaker = espeakng.Speaker()
    #mySpeaker.say('Initializing Baxter')
    

def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning" + Commander)
        print("Good Morning " + Commander)
    elif hour>=12 and hour<18:
        speak("Good Afternoon" + Commander)
        print("Good Afternoon " + Commander)   
    else:
        speak("Good Evening" + Commander) 
        print("Good Evening " + Commander) 
        speak("How may I be of service?")
        print("How may I be of service?")   

def listenCommand():
    command=0
    hear = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = hear.listen(source)
#---------------------------
# Uses google API to listen
    try:
        print("Recognizing...")
        command = hear.recognize_google(audio, language='en-in')
        print(f'{Commander} : {command}\n')

    except:
            pass

    return command 

#--------------------------------

speak("Initializing Baxter..........")
wishMe()

def main():
    command = listenCommand()
    command=str(command).lower()

    #-------------------------------------------------------------------------------------
                            #Search Wikipedia (General Info)
    #-------------------------------------------------------------------------------------
    if ('who is' in command) or ('what is the' in command) or ('what is a' in command):
        speak('Searching Wikipedia...')
        command = command.replace("who is","")
        command = command.replace("what is the","")
        command = command.replace("what is a","")
        results = wikipedia.summary(command, sentences = 2)
        print("Baxter:",results)
        return speak(results) 
    #-------------------------------------------------------------------------------------
                    #Search Wolfram Alpha (Math/Conversions, Definitions)
    #-------------------------------------------------------------------------------------
    elif ('calculate' in command) or ('what is' in command) or ('define' in command):
        speak('Searching Wolfram Alpha...')
        command = command.replace("calculate","")
        command = command.replace("what is","")
        command = command.replace("define","")
        # Wolframalpha App Id
        appId = 'JH9XHR-W9J76L7H5A'
        # Wolfram Instance
        client = wolframalpha.Client(appId)
        res = client.query(''.join(command))
        results = next(res.results).text
        print("Baxter:",results)
        return speak(results) 
    #-------------------------------------------------------------------------------------
                                    #Search News
    #-------------------------------------------------------------------------------------
    elif ('news' in command):
        speak('Searching news networks...')
        command = command.replace("news","")
        url='https://www.google.com/search?q=windsor+news&client=firefox-b-d&source=lnms&tbm=nws&sa=X&ved=2ahUKEwjFr5SwoJb1AhXELs0KHdabBAEQ_AUoAXoECAEQAw&biw=1024&bih=486'
        results = requests.get(url)
        soup = BeautifulSoup(results.text, 'html.parser')
        headlines = soup.find('body').find_all('h3')
        for x in headlines:
            print("Baxter:",x.text.strip())
        return speak(results) 
    #-------------------------------------------------------------------------------------
                                        #Search Weather
    #-------------------------------------------------------------------------------------
    elif ('weather' in command):
        speak('Searching weather networks...')
        command = command.replace("weather","")
        #Call weather data  for today:
        displayWeatherData()

    elif ('weather for the week' in command):
        speak('Searching weather networks...')
        command = command.replace("weather for the week","")
        #Call weather data for the week:
        displayWeeksWeatherData()
    #-------------------------------------------------------------------------------------
                                        #Tell Time
    #-------------------------------------------------------------------------------------
    elif ('time' in command):
        speak('Scanning local clock networks...')
        command = command.replace("time","")
        strTime = datetime.datetime.now().strftime("%I:%M%P")
        speak("The time is {strTime}")
        print("Baxter:", "The time is", strTime)
    #-------------------------------------------------------------------------------------
                                #Enter the Matrix (Easter Egg)
    #-------------------------------------------------------------------------------------
    elif ('matrix' in command):
        speak('Entering the matrix...')
        print("Baxter:","Taking the red pill...")
        command = command.replace("matrix","")
        time.sleep(2)
        os.system("cmatrix")
    #-------------------------------------------------------------------------------------

    #-------------------------------------------------------------------------------------
                                #Stop Program/Script Command
    #-------------------------------------------------------------------------------------
    elif ('stop' in command) or ('shutdown' in command) or ('quit' in command):
        speak("Shutting Down...")
        return exit()
       
    else:
        return 0 
    #-------------------------------------------------------------------------------------

while True:
    main()  
Reply


Messages In This Thread
Matching Exact String(s) - by Extra - Jan-10-2022, 10:43 PM
RE: Matching Exact String(s) - by BashBedlam - Jan-11-2022, 03:06 AM
RE: Matching Exact String(s) - by Extra - Jan-11-2022, 11:42 PM
RE: Matching Exact String(s) - by BashBedlam - Jan-12-2022, 12:50 AM
RE: Matching Exact String(s) - by Extra - Jan-12-2022, 04:06 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Matching string from a file tester_V 5 501 Mar-05-2024, 05:46 AM
Last Post: Danishhafeez
Question in this code, I input Key_word, it can not find although all data was exact Help me! duchien04x4 3 1,099 Aug-31-2023, 05:36 PM
Last Post: deanhystad
  matching a repeating string Skaperen 2 1,286 Jun-23-2022, 10:34 PM
Last Post: Skaperen
  Matching multiple parts in string fozz 31 6,516 Jun-13-2022, 09:38 AM
Last Post: fozz
  replace exact word marfer 1 6,258 Oct-11-2021, 07:08 PM
Last Post: snippsat
  Assistance with running a few lines of code at an EXACT time nethatar 5 3,328 Feb-24-2021, 10:43 PM
Last Post: nilamo
  Exact Match Kristenl2784 2 2,903 Jul-26-2020, 03:29 PM
Last Post: Kristenl2784
  Two exact "Fors" giving me different results? FilGonca 2 2,060 May-04-2020, 12:36 PM
Last Post: FilGonca
  Confusion in exact term used for ? ift38375 2 2,604 Jul-22-2019, 08:58 AM
Last Post: buran
  Finding exact phrase in list graham23s 2 2,940 Mar-13-2019, 06:47 PM
Last Post: graham23s

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020