У меня проблемы с запуском этого кода, потому что он продолжает выполнять случайные части операторов if в Python - PullRequest
0 голосов
/ 19 июня 2020

Итак, я работаю над программой типа помощника, но я планирую настроить ее немного больше для более конкретного использования, чем ваш обычный помощник. У меня проблема с моим кодом, когда иногда он запускал случайный Оператор if рядом с оператором if, который должен был быть выполнен, и иногда он просто выдает ошибку, и я понятия не имею, почему это происходит, по крайней мере, пока ... Любая помощь будет принята с благодарностью.

EDIT: Я обновил код, чтобы он содержал elif (CODE Update # 2)

def check_audio():
cmdtext = get_audio()
print("CMDTEXT-You said: " + cmdtext)

try:
    if any(x.lower() in cmdtext for x in ["Hey", "Hello", "Ahoi"]):
        hellos = ["Hey there!", "Hi!", "How's it going?", "Well.. Hello there!"]
        stalk(random.choice(hellos))
    elif "schedule" in cmdtext:
        if "days" or "day" in cmdtext:
            number = re.search(r'\d+', cmdtext).group()
            if w2n.word_to_num(cmdtext) == int:
                get_events(w2n.word_to_num(cmdtext), service)
            elif "Week" in cmdtext:
                get_events(7, service)
                if w2n.word_to_num(cmdtext) & "Week" in cmdtext:
                    combined = w2n.word_to_num(cmdtext) * 7
                    get_events(number, service)

    elif "quit" in cmdtext:
        quitcount + 1
        print(quitcount)
        byebyes = ["Bye Bye!", "See you later!", "Cya later alligator", "See you soon!"]
        stalk(random.choice(byebyes))
        quit()
    elif "go back" in cmdtext:
        #This part is not currently functional and does absolutely nothing
        while "go back" in cmdtext:
            break
    elif "open" in cmdtext:
        if "Notepad" in cmdtext:
            subprocess.Popen([r'C:\Program Files\Notepad++\\Notepad++.exe'])
        elif "Chrome" in cmdtext:
            subprocess.Popen([r'C:\Program Files (x86)\Google\Chrome\Application\\Chrome.exe'])
        elif "Discord" in cmdtext:
            subprocess.Popen([r'C:\Users\CelestialMavis\AppData\Local\Discord\app-0.0.306\\Discord.exe'])
        elif "Steam" in cmdtext:
            subprocess.Popen([r'C:\Program Files (x86)\Steam\\Steam.exe'])
        else:
            stalk("I did not recognize that program name")
    if any(y.lower() in cmdtext for y in ["Rick Roll", "rickroll"]):
        webbrowser.open_new_tab("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
    else:
        print("I don't recognise this command")

except Exception as e:
    print("Error" + e)
    stalk("I didn't quite get that")

EDIT # 1, есть ли способ вернуть программу go к предыдущему файлу .py, где код сначала запускался и запускался в определенный момент я запускаю прослушиватель в первом файле, который прослушивает команды, и как только он получает команду, он запускает этот файл .py, который идентифицирует команду, и проблема в том, что после ее выполнения он продолжает прослушивать команды вместо того, чтобы возвращаться чтобы прослушать ключевое слово, вот код, который я использую:

def mainOps():

   while beginop != "Quit" or "Exit":
       SEGI.check_audio()

# Listen for Keyword from Microphone!
recog = spcrec.Recognizer()

# This is the keyword that will be used to activate the system in this case its "hey Wendy"
cmdwrd = 'hey Wendy'
# This is the keyword that will cause the program to quit
cmdwrdqt = 'quit'

# This while loop listens for the keyword and then executes mainOps() if it's detected

with spcrec.Microphone() as source:
#with spcrec.AudioFile('keyword.wav') as source:

    print(f"Hey! Im VASE")
    print(f"Please say {cmdwrd.capitalize()} to speak with Wendy or say {cmdwrdqt.capitalize()} to End the program")
    # The variable below dictates what VASE TTS says upon startup
    Greeting = f"Hey! I am VASE"
    whattosay = f"Please say {cmdwrd} to speak with Wendy or say {cmdwrdqt} to End the program"

    # Sending the variable to the TTS function in order to create an MP3 file of the text and play it
    vtts.VaseTTS(whattosay) #Strangely this only works once and I have no idea why.
    # Attempted to call the function again using different text but it doesn't function yet
    vso = "Vase Online"
    print(vso)
    #STa.talk(vso)

    # Code below continues to listen to what you say and does something when it hears the keyword
    while True:
        try:
            STa.detectionwords = STa.get_audio()

            if (STa.check_audio() == True):
                while True:
                 mainOps()
            else:
                print("Please speak again, keyword not detected")
        except Exception as e:
            print('No keywords detected, please say the command to begin again')
            print(e)

Ответы [ 3 ]

0 голосов
/ 19 июня 2020
if "Hey".lower() or "Hello".lower() or "Ahoi".lower() in cmdtext:

Много утверждений, как указано выше, может означать иное, чем ваш запрос, может быть выражено так

if "Hey".lower() in cmdtext or "Hello".lower() in cmdtext or "Ahoi".lower() in cmdtext:

или, может быть, вы делаете это так

from itertools import repeat

cmdtext = 'John, good morning'
cmdtext = cmdtext.lower()
print(any(map(str.__contains__, repeat(cmdtext), ['hey', 'hello', 'ahoi'])))
0 голосов
/ 19 июня 2020

Что-то похожее на ответы выше, попробуйте это.

if cmdtext in ("Hey".lower(),"Hello".lower(),"Ahoi".lower()):

Закомментируйте while l oop и посмотрите, работает ли он, поскольку в данный момент его нельзя использовать.

0 голосов
/ 19 июня 2020

Это (и подобные ему строки)

if "Hey".lower() or "Hello".lower() or "Ahoi".lower() in cmdtext:

должно быть

if any(x.lower() in cmdtext for x in ["Hey", "Hello", "Ahoi"]):

in не «распределяется» по множеству or s, аналогично умножению, распределяющему по сложение по математике. Учитывая приоритет or и in, ваш оригинал эквивалентен

if "Hey".lower() or "Hello".lower() or ("Ahoi".lower() in cmdtext):

not

# Legal, but long-winded
if "Hey".lower() in cmdtext or "Hello".lower() in cmdtext or "Ahoi".lower() in cmdtext:

Поскольку "Hey".lower() - непустая строка, два других выражения никогда не оцениваются, и все это True, потому что "Hey".lower() истинно.

...