#python #python-3.x #python-3.9 #writefile
Вопрос:
Я делаю помощника, и я хочу, чтобы он записывал в файл все разговоры, которые я говорил, но это происходит, когда я запускаю его «UnboundLocalError: локальная переменная» открыта», на которую ссылаются перед назначением», и я пытаюсь многими способами исправить это, но я не смог это исправить. Надеюсь, кто-нибудь сможет помочь мне это исправить. Спасибо за любую помощь, вот мой код
#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=viamp;sl=enamp;tl=viamp;op=translate')
elif ("open internet") in you:
Jarvis_brain("opening internet")
open = "C:Program Files (x86)BraveSoftwareBrave-BrowserApplicationBrave.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)
#Newamp;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:UsersPCDocumentsCodeassistantJarvis.py", line 181, in <module>
main()
File "c:UsersPCDocumentsCodeassistantJarvis.py", line 86, in main
with open ("Jarvis.txt", "a") as Jarvis:
UnboundLocalError: local variable 'open' referenced before assignment
Спасибо за любую помощь
Комментарии:
1. Вы переопределяете
open
ключевое словоopen = "C:Program Files (x86)BraveSoftwareBrave-BrowserApplicationBrave.exe"
Ответ №1:
Это связано с тем, что вы определили команду open, которая является одной из основных команд Python, как переменную.
На данный момент похоже, что вы вставляете эту строку в и пытаетесь открыть файл с помощью строки, что приводит к ошибке.
open = "C:Program Files (x86)BraveSoftwareBrave-BrowserApplicationBrave.exe"
Переименуйте открытую переменную, которую вы определили в строке 146, в другое имя, open_
чтобы решить вашу проблему.