Home > Back-end >  Find A value in list , if there are multiple value print all the values else print the corresponding
Find A value in list , if there are multiple value print all the values else print the corresponding

Time:03-19

I have two lists :

Keyword = ['Dog', 'Cat', 'White Cat', 'Lion', 'Black Cat']
Definition = ['Mans Best Friend', 'The cat is a domestic species of a small carnivorous mammal', 'White  cats are cute', 'Lions are Carnivores Wild Animal', 'Black Cats are Black in color']

I am getting a voice input in 'query' from the following command:

import speech_recognition as sr

def takeCommand():
     
    r = sr.Recognizer()
     
    with sr.Microphone() as source:
         
        print("Listening...")
        r.pause_threshold = 1
        audio = r.listen(source)
  
    try:
        print("Recognizing...")   
        query = r.recognize_google(audio, language ='en-in')
        print(f"User said: {query}\n")
  
    except Exception as e:
        print(e)   
        print("Unable to Recognize your voice.") 
        return "None"
     
    return query

query = takeCommand().Capitalize()

Now if the query contains Dog in it I want to print the corresponding definition from the list i.e. 'Man's Best Friend', If the query contains Cat , I want to show the user that there are multiple Keywords that have 'Cat' in them i.e. 'Cat', 'White Cat', 'Black Cat' and if the word inside query isn't in the list I want to print "No keywords Found, Please check your Keyword"

Does anyone has an idea on how to solve this?

Input output for different cases:

Input: query has 'Dog' in it. The program should check for if there are more than 1 word that has Dog in it. If Yes it should print all the keywords that has Dog in it, if No then it should print the corresponding definition . In this case of Keywords the output for Dog should be the corresponding definition i.e. 'Mans Best Friend'.

Input: Query has 'Cat' in it. In this case of keywords there are 3 keywords that have cat in them i.e. 'Cat' , 'Black Cat', 'White Cat' So here the code should Print these Keywords instead of their definition. So output of this case : We have found multiple keywords : 'Cat' , 'Black Cat', 'White Cat'

Input : Query has 'Panther' in it. There is no Panther in Keywords So it should print "There are no Matching Keywords".

CodePudding user response:

Try this code

import speech_recognition as sr

def takeCommand():
     
    r = sr.Recognizer()
     
    with sr.Microphone() as source:
         
        print("Listening...")
        r.pause_threshold = 1
        audio = r.listen(source)
  
    try:
        print("Recognizing...")   
        query = r.recognize_google(audio, language ='en-in')
        print(f"User said: {query}\n")
  
    except Exception as e:
        print(e)   
        print("Unable to Recognize your voice.") 
        return "None"
     
    return query

def there_exists(terms):
    for term in terms:
        if term in query:
            return True


Definition = ['Mans Best Friend', 'The cat is a domestic species of a small carnivorous mammal', 'White  cats are cute', 'Lions are Carnivores Wild Animal', 'Black Cats are Black in color']

while True:
    query = takeCommand().lower()

    if there_exists(['dog']):
        print(Definition[0])
    
    elif there_exists(['cat']):
        print(Definition[1])

    elif there_exists(['white cat']):
        print(Definition[2])

    elif there_exists(['lion']):
        print(Definition[3])

    elif there_exists(['black cat']):
        print(Definition[4])

    else:
        print("No keywords Found, Please check your Keyword")

It's better not to use capitalize() as for example if the user inputs 'dog' the program won't respond as it expects 'Dog'. You could use string similarity methods like Levenshtein distance to see if the query and keyword matches

CodePudding user response:

Keyword = ['Dog', 'Cat', 'White Cat', 'Lion', 'Black Cat']
Definition = ['Mans Best Friend', 'The cat is a domestic species of a small carnivorous mammal', 'White  cats are cute', 'Lions are Carnivores Wild Animal', 'Black Cats are Black in color']

def take_cmd(cmd):
    multiple_val=[]
    if cmd in Keyword:
        for i,j in enumerate(Keyword):
            if cmd in j:
                multiple_val.append((i,j))
        if len(multiple_val)>1:
            i_removed=[j for i in multiple_val for j in i if type(j)!=int]
            print(f"We have found multiple keywords : {i_removed}")
        else:
            print(Definition[Keyword.index(cmd)])
    else:
        print("There are no Matching Keywords")

What this code does is:

  1. Checks if the value inputed exists in the Keyword or not, if not then would return "There are no Matching Keywords".
  2. If the value exists, then would check if there are multiple instances or the value is available in multiple indexes or not.
  3. If that returns true as well then it appends it to multiple_vals. If length of multiple_val if greater than 1 then only it would show f"We have found multiple keywords : {i_removed}".
  4. otherwise shows the corresponding index in Definition.
  • Related