How to open a file if it matches the filename given ( filename obtained using speech recognition)

223 Views Asked by At

I'm trying to make a script that uses the speech recognition module to listen to your voice and accordingly to what it heard, using that as the filename, if it is in a specific folder (giving the path to it) open the file... However I'm stuck because I can't get the last for loop working (the one that right now should just print the filename if it is in the folder).

import speech_recognition as sr
import os 


search_path = 'C:/Users/andre/Desktop/foto_coso_python'
result = []

recognizer_instance = sr.Recognizer()

with sr.Microphone() as source:
    recognizer_instance.adjust_for_ambient_noise(source)
    print("I'm listening...")
    print()
    audio = recognizer_instance.listen(source)
    #print('Printing what I heard...')

try:
    text = recognizer_instance.recognize_google(audio, language='it-IT').upper()
    print(text)
except Exception as e:
    print(e)

list_text = text.split(' ')  #splits the text in single words
#print(list_text)


for root, dir, files in os.walk(search_path):
    for word in list_text:
        if word in files:
            result.append(os.path.join(root, word))


print(result)

EDIT Thanks to @loa_in_ I figured out that loop

for word in list_text:
    for root, dir, files in os.walk(search_path):
        for filename in files:
            if word.lower() in filename.lower():
                result.append(filename)

Now the ouuput of the code is the file name (if in the folder).

1

There are 1 best solutions below

1
On

If you are using Windows (I assume so from your paths) then you should not really compare filenames as word in files because that does a case-sensitive exact match:

  • "file" and "File" won't match
  • "file" and "File.txt" won't match
  • "file" and "file.txt" won't match
  • "file" and "this_file_here" won't match
  • only "file" and "file" will match

To search for a word in the files array in a less strict manner you must loop: for filename in files and check if filename.lower() contains word.lower() - in other words: check for substring after converting both strings to same case (whether it's lowercase or uppercase).