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
#2
Here, try these on for size:
if ('who is' in command) or ('what is the' in command) or ('what is a' in command):
	if ('time' not 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) 

elif ('weather' in command):
   if ('week' in command):
	   speak('Searching weather networks...')
	   command = command.replace("weather for the week","")
	   #Call weather data for the week:
	   displayWeeksWeatherData()
	else :
	   speak('Searching weather networks...')
	   command = command.replace("weather","")
	   #Call weather data  for today:
	   displayWeatherData()
Reply
#3
(Jan-11-2022, 03:06 AM)BashBedlam Wrote: Here, try these on for size:
if ('who is' in command) or ('what is the' in command) or ('what is a' in command):
	if ('time' not 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) 

elif ('weather' in command):
   if ('week' in command):
	   speak('Searching weather networks...')
	   command = command.replace("weather for the week","")
	   #Call weather data for the week:
	   displayWeeksWeatherData()
	else :
	   speak('Searching weather networks...')
	   command = command.replace("weather","")
	   #Call weather data  for today:
	   displayWeatherData()

Thanks for the helpful response.

The time manages to work (I can say "What is the time?" & "What time is it?" and it will display the time) however, the weather still won't work. If I say "What is the weather?" or "What is the weather for the week?" it will give me the definition of the weather, but not the actual forecast that it's supposed to. I think it's still getting confused with the Wikipedia search statement.

Any ideas on how to get it to work?

I really appreciate your help.
Thanks again.

Side Note:
In order for me to get the "What is the time?" command to work I had to change the elif of the weather statement to an if (which I think is kind of strange, but hey it works, so I'm not complaining) so it wouldn't give me the definition of the word time.
if ('who is' in command) or ('what is the' in command) or ('what is a' in command):
	if ('time' not 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) 

if ('weather' in command):
   if ('week' in command):
	   speak('Searching weather networks...')
	   command = command.replace("weather for the week","")
	   #Call weather data for the week:
	   displayWeeksWeatherData()
	else :
	   speak('Searching weather networks...')
	   command = command.replace("weather","")
	   #Call weather data  for today:
	   displayWeatherData()
Reply
#4
Try testing for the word weather in the command before you test for 'What is'. That way it might not give the definition.
Reply
#5
(Jan-12-2022, 12:50 AM)BashBedlam Wrote: Try testing for the word weather in the command before you test for 'What is'. That way it might not give the definition.

Thanks for the help. It worked.

Now If I say "What is the weather" it will search wolfram alpha for the current weather in my city, But if I say "What's the weather?" It will jump to my weather script and display those results. If I say "What is the weather for the week" it will search wolfram alpha for the week's forecast, and if I say "What's the weather for the week"/"What's the weather this week" It will pull up the results from my weather script.

The only thing that it interfered with was the news command, but I fixed that by changing it's elif to an if statement

Once again,

Thanks for your help. It was much appreciated.

(The working code in case anyone's interested):
#!/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 ('weather' not in command):
        if ('who is' in command) or ('what is the' in command) or ('what is a' in command):
            if ('time' not 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
    #-------------------------------------------------------------------------------------
    if ('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
    #-------------------------------------------------------------------------------------
    if ('weather' in command):
        if ('week' in command):
            speak('Searching weather networks...')
            command = command.replace("weather for the week","")
            #Call weather data for the week:
            displayWeeksWeatherData()
        else :
            speak('Searching weather networks...')
            command = command.replace("weather","")
            #Call weather data  for today:
            displayWeatherData()
    #-------------------------------------------------------------------------------------
                                        #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()  
BashBedlam likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Matching string from a file tester_V 5 453 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,056 Aug-31-2023, 05:36 PM
Last Post: deanhystad
  matching a repeating string Skaperen 2 1,256 Jun-23-2022, 10:34 PM
Last Post: Skaperen
  Matching multiple parts in string fozz 31 6,349 Jun-13-2022, 09:38 AM
Last Post: fozz
  replace exact word marfer 1 6,188 Oct-11-2021, 07:08 PM
Last Post: snippsat
  Assistance with running a few lines of code at an EXACT time nethatar 5 3,271 Feb-24-2021, 10:43 PM
Last Post: nilamo
  Exact Match Kristenl2784 2 2,849 Jul-26-2020, 03:29 PM
Last Post: Kristenl2784
  Two exact "Fors" giving me different results? FilGonca 2 2,023 May-04-2020, 12:36 PM
Last Post: FilGonca
  Confusion in exact term used for ? ift38375 2 2,573 Jul-22-2019, 08:58 AM
Last Post: buran
  Finding exact phrase in list graham23s 2 2,913 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