How to fix "UnboundLocalError: local variable 'open' referenced before assignment" in write file?

How to fix "UnboundLocalError: local variable 'open' referenced before assignment" in write file?

我正在做一个助手,我想让它把我说过的所有对话都写成文件,但是当我 运行 它出现“UnboundLocalError: local variable 'open' referenced before assignment”并且我尝试了很多方法来修复它,但我无法修复它。希望任何人都可以帮助我修复它。 感谢您的帮助 这是我的代码

#import
import datetime
import os
import pyautogui
import pyjokes
import pyttsx3
import pywhatkit
import requests
import smtplib
import speech_recognition as sr
import webbrowser as we
from email.message import EmailMessage
from datetime import date
from newsapi import NewsApiClient
import random
import os
import wikipedia
from subprocess import run
from typing import Text
import time






user = "Tom" #your name
assistant= "Jarvis" # Iron man Fan

Jarvis_mouth = pyttsx3.init()
Jarvis_mouth.setProperty("rate", 165)
voices = Jarvis_mouth.getProperty("voices")

# For Mail voice AKA Jarvis
Jarvis_mouth.setProperty("voice", voices[1].id)

def Jarvis_brain(audio):
    robot = Jarvis_brain
    print("Jarvis: " + audio)
    Jarvis_mouth.say(audio)
    Jarvis_mouth.runAndWait()

#Jarvis speech 
#Jarvis_ear = listener
#Jarvis_brain = speak
#Jarvis_mouth = engine
#you = command

def inputCommand():
    # you = input() # For getting input from CLI
    Jarvis_ear = sr.Recognizer()
    you = ""
    with sr.Microphone(device_index=1) as mic:
        print("Listening...")
        Jarvis_ear.pause_threshold = 1
        try:
            you = Jarvis_ear.recognize_google(Jarvis_ear.listen(mic, timeout=3), language="en-IN")
        except Exception as e:
            Jarvis_brain(" ")
        except:
            you = ""
        print("You: " + you)
    return you
print("Jarvis AI system is booting, please wait a moment")
Jarvis_brain("Start the system, your AI personal assistant Jarvis")



def greet():
    hour=datetime.datetime.now().hour
    if hour>=0 and hour<12:
        Jarvis_brain(f"Hello, Good Morning {user}")
        print("Hello,Good Morning")
    elif hour>=12 and hour<18:
        Jarvis_brain(f"Hello, Good Afternoon {user}")
        print("Hello, Good Afternoon")
    else:
        Jarvis_brain(f"Hello, Good Evening {user}")
        print("Hello,Good Evening")
greet()        


    
def main():
    while True:
        with open ("Jarvis.txt", "a") as Jarvis:
            Jarvis.write("Jarvis: " + str(Jarvis_brain) + "\n" + "You: " + str(you) + "\n")
        # Getting input from the user
        you = inputCommand().lower()

        #General question.
        if ("hello" in you) or ("Hi" in you):
            Jarvis_brain(random.choice(["how may i help you, sir.","Hi,sir"]))

        elif ("time" in you):
            now = datetime.datetime.now()
            robot_brain = now.strftime("%H hour %M minutes %S seconds")
            Jarvis_brain(robot_brain)

        elif ("date" in you):
            today = date.today()
            robot_brain = today.strftime("%B %d, %Y")
            Jarvis_brain(robot_brain)

        elif ("joke" in you):
            Jarvis_brain(pyjokes.get_joke())

        elif "president of America" in you:
            Jarvis_brain("Donald Trump")

        #open application
        elif ("play" in you):
            song = you.replace('play', '')
            Jarvis_brain('playing ' + song)
            pywhatkit.playonyt(song)
        
        elif ("open youtube" in you):
            Jarvis_brain("opening YouTube")
            we.open('https://www.youtube.com/')    

        elif ("open google" in you):
            Jarvis_brain("opening google")
            we.open('https://www.google.com/')    

        elif "information" in you:
            you = you.replace("find imformation", "")
            Jarvis_brain("what news you what to know about")
            topic=inputCommand()
            Jarvis_brain("open " + topic)
            we.open("https://www.google.com/search?q=" + topic)

        elif ("open gmail" in you):
            Jarvis_brain("opening gmail")
            we.open('https://mail.google.com/mail/u/2/#inbox')    
        
        elif "vietnamese translate" in you:
            Jarvis_brain("opening Vietnamese Translate")
            we.open('https://translate.google.com/?hl=vi')    

        elif "english translate" in you:
            Jarvis_brain("opening English Translate")
            we.open('https://translate.google.com/?hl=vi&sl=en&tl=vi&op=translate') 

        elif ("open internet") in you:
            Jarvis_brain("opening internet")
            open = "C:\Program Files (x86)\BraveSoftware\Brave-Browser\Application\Brave.exe"
            os.startfile(open)

        elif "wikipedia" in you:
            you = you.replace("wikipedia", "")
            Jarvis_brain("what topic you need to listen to")
            topic=inputCommand()
            results = wikipedia.summary(topic, sentences=2, auto_suggest=False, redirect=True)
            print(results)
            Jarvis_brain(results)


    #New&Covid-19
        elif ("news" in you): 
            newsapi = NewsApiClient(api_key='d4eb31a4b9f34011a0c243d47b9aed4d')
            Jarvis_brain("What topic you need the news about")
            topic = inputCommand()
            data = newsapi.get_top_headlines(
                q=topic, language="en", page_size=5)
            newsData = data["articles"]
            for y in newsData:
                Jarvis_brain(y["description"])

        elif ("covid-19" in you):
            r = requests.get('https://coronavirus-19-api.herokuapp.com/all').json()
            Jarvis_brain(f'Confirmed Cases: {r["cases"]} \nDeaths: {r["deaths"]} \nRecovered {r["recovered"]}')

        else:
            if "goodbye" in you:
                hour = datetime.datetime.now().hour
                if (hour >= 21) and (hour < 5):
                    Jarvis_brain(f"Good Night {user}! Have a nice Sleep")
                else:
                    Jarvis_brain(f"Bye {user}")
                quit()
main()   

这是我的终端

Traceback (most recent call last):
  File "c:\Users\PC\Documents\Code\assistant\Jarvis.py", line 181, in <module>
    main()
  File "c:\Users\PC\Documents\Code\assistant\Jarvis.py", line 86, in main
    with open ("Jarvis.txt", "a") as Jarvis:
UnboundLocalError: local variable 'open' referenced before assignment

感谢您的帮助

这是因为您已经将 open 命令定义为一个变量,它是主要的 Python 命令之一。

此时,您似乎将此字符串放入 并尝试使用该字符串打开文件,这会导致错误。

open = "C:\Program Files (x86)\BraveSoftware\Brave-Browser\Application\Brave.exe"

将您在第 146 行定义的开放变量重命名为另一个名称,如 open_ 以解决您的问题。