NameError: free variable 'csv' referenced before assignment in enclosing scope
NameError: free variable 'csv' referenced before assignment in enclosing scope
我是 Python 的新手,这可能是一个菜鸟问题,我已经尝试 google 并搜索解决方案,但我未能理解,请善待,如果有人可以指导我完成这个吗?
我正在尝试在另一个函数中回调我的函数:
import csv
#import other libraries
#.......................................
def suara():
fs = 44100
seconds = 2
myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)
print("Memulai: Silahkan berbicara sekarang!")
sd.wait()
print("Selesai")
write((os.path.join('data', 'recordings', 'test', '0_login.wav')), fs, myrecording)
CREATE_CSV_FILES = True
# Defines the names of the CSV files
TRAIN_CSV_FILE = "train.csv"
TEST_CSV_FILE = "test.csv"
def extractWavFeatures(soundFilesFolder, csvFileName):
print("The features of the files in the folder "+soundFilesFolder+" will be saved to "+csvFileName)
header = 'filename chroma_stft rmse spectral_centroid spectral_bandwidth rolloff zero_crossing_rate'
for i in range(1, 21):
header += f' mfcc{i}'
header += ' label'
header = header.split()
print('CSV Header: ', header)
file = open(csvFileName, 'w', newline='')
#with file:
writer = csv.writer(file)
writer.writerow(header)
genres = '1 2 3 4 5 6 7 8 9 0'.split()
for filename in os.listdir(soundFilesFolder):
number = f'{soundFilesFolder}/{filename}'
# print(number)
y, sr = librosa.load(number, mono=True, duration=30)
# remove leading and trailing silence
y, index = librosa.effects.trim(y)
chroma_stft = librosa.feature.chroma_stft(y=y, sr=sr)
rmse = librosa.feature.rms(y=y)
spec_cent = librosa.feature.spectral_centroid(y=y, sr=sr)
spec_bw = librosa.feature.spectral_bandwidth(y=y, sr=sr)
rolloff = librosa.feature.spectral_rolloff(y=y, sr=sr)
zcr = librosa.feature.zero_crossing_rate(y)
mfcc = librosa.feature.mfcc(y=y, sr=sr)
to_append = f'{filename} {np.mean(chroma_stft)} {np.mean(rmse)} {np.mean(spec_cent)} {np.mean(spec_bw)} {np.mean(rolloff)} {np.mean(zcr)}'
for e in mfcc:
to_append += f' {np.mean(e)}'
writer.writerow(to_append.split())
file.close()
print("End of extractWavFeatures")
#........................................................
我试图在这里回调这个函数:
def access(option):
global name
if(option=="login"):
name = input("Masukkan ID: ")
password = input("Masukkan Password: ")
login(name,password)
else:
suara()
def begin():
global option
print("="*45)
print(" | Selamat datang |")
print("-"*45)
print("Ketik 'login' jika anda ingin membuka pintu via nama dan password")
print("Ketik 'suara' jika anda inin membuka pintu via suara")
print("="*45)
option = input("slahkan masukkan (login/suara): ")
if(option!="login" and option!="suara"):
begin()
begin()
access(option)
但是我得到了以下错误:
(cloning2) C:\Users\thosiba\speaker-recognition>C:/Users/thosiba/Anaconda3/envs/cloning2/python.exe c:/Users/thosiba/speaker-recognition/login2.py
=============================================
| Selamat datang |
---------------------------------------------
Ketik 'login' jika anda ingin membuka pintu via nama dan password
Ketik 'suara' jika anda inin membuka pintu via suara
=============================================
slahkan masukkan (login/suara): suara
Memulai: Silahkan berbicara sekarang!
Selesai
The features of the files in the folder C:/Users/thosiba/speaker-recognition/data/recordings/train will be saved to train.csv
CSV Header: ['filename', 'chroma_stft', 'rmse', 'spectral_centroid', 'spectral_bandwidth', 'rolloff', 'zero_crossing_rate', 'mfcc1', 'mfcc2', 'mfcc3', 'mfcc4', 'mfcc5', 'mfcc6', 'mfcc7', 'mfcc8', 'mfcc9', 'mfcc10', 'mfcc11', 'mfcc12', 'mfcc13', 'mfcc14', 'mfcc15', 'mfcc16', 'mfcc17', 'mfcc18', 'mfcc19', 'mfcc20', 'label']
Traceback (most recent call last):
File "c:/Users/thosiba/speaker-recognition/login2.py", line 236, in <module>
access(option)
File "c:/Users/thosiba/speaker-recognition/login2.py", line 221, in access
suara()
File "c:/Users/thosiba/speaker-recognition/login2.py", line 79, in suara
extractWavFeatures("C:/Users/thosiba/speaker-recognition/data/recordings/train", TRAIN_CSV_FILE)
File "c:/Users/thosiba/speaker-recognition/login2.py", line 55, in extractWavFeatures
writer = csv.writer(file)
NameError: free variable 'csv' referenced before assignment in enclosing scope
我很确定它与调用函数或将其标记为全局函数有关,但我真的不明白在这种情况下如何解决它。很抱歉问了这么长的问题,因为我不知道如何解释得更好。
如果您在文件中的任何位置(甚至在错误行下方)命名变量 csv
,就会导致此错误。尝试将该变量的名称更改为其他名称。
我是 Python 的新手,这可能是一个菜鸟问题,我已经尝试 google 并搜索解决方案,但我未能理解,请善待,如果有人可以指导我完成这个吗?
我正在尝试在另一个函数中回调我的函数:
import csv
#import other libraries
#.......................................
def suara():
fs = 44100
seconds = 2
myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)
print("Memulai: Silahkan berbicara sekarang!")
sd.wait()
print("Selesai")
write((os.path.join('data', 'recordings', 'test', '0_login.wav')), fs, myrecording)
CREATE_CSV_FILES = True
# Defines the names of the CSV files
TRAIN_CSV_FILE = "train.csv"
TEST_CSV_FILE = "test.csv"
def extractWavFeatures(soundFilesFolder, csvFileName):
print("The features of the files in the folder "+soundFilesFolder+" will be saved to "+csvFileName)
header = 'filename chroma_stft rmse spectral_centroid spectral_bandwidth rolloff zero_crossing_rate'
for i in range(1, 21):
header += f' mfcc{i}'
header += ' label'
header = header.split()
print('CSV Header: ', header)
file = open(csvFileName, 'w', newline='')
#with file:
writer = csv.writer(file)
writer.writerow(header)
genres = '1 2 3 4 5 6 7 8 9 0'.split()
for filename in os.listdir(soundFilesFolder):
number = f'{soundFilesFolder}/{filename}'
# print(number)
y, sr = librosa.load(number, mono=True, duration=30)
# remove leading and trailing silence
y, index = librosa.effects.trim(y)
chroma_stft = librosa.feature.chroma_stft(y=y, sr=sr)
rmse = librosa.feature.rms(y=y)
spec_cent = librosa.feature.spectral_centroid(y=y, sr=sr)
spec_bw = librosa.feature.spectral_bandwidth(y=y, sr=sr)
rolloff = librosa.feature.spectral_rolloff(y=y, sr=sr)
zcr = librosa.feature.zero_crossing_rate(y)
mfcc = librosa.feature.mfcc(y=y, sr=sr)
to_append = f'{filename} {np.mean(chroma_stft)} {np.mean(rmse)} {np.mean(spec_cent)} {np.mean(spec_bw)} {np.mean(rolloff)} {np.mean(zcr)}'
for e in mfcc:
to_append += f' {np.mean(e)}'
writer.writerow(to_append.split())
file.close()
print("End of extractWavFeatures")
#........................................................
我试图在这里回调这个函数:
def access(option):
global name
if(option=="login"):
name = input("Masukkan ID: ")
password = input("Masukkan Password: ")
login(name,password)
else:
suara()
def begin():
global option
print("="*45)
print(" | Selamat datang |")
print("-"*45)
print("Ketik 'login' jika anda ingin membuka pintu via nama dan password")
print("Ketik 'suara' jika anda inin membuka pintu via suara")
print("="*45)
option = input("slahkan masukkan (login/suara): ")
if(option!="login" and option!="suara"):
begin()
begin()
access(option)
但是我得到了以下错误:
(cloning2) C:\Users\thosiba\speaker-recognition>C:/Users/thosiba/Anaconda3/envs/cloning2/python.exe c:/Users/thosiba/speaker-recognition/login2.py
=============================================
| Selamat datang |
---------------------------------------------
Ketik 'login' jika anda ingin membuka pintu via nama dan password
Ketik 'suara' jika anda inin membuka pintu via suara
=============================================
slahkan masukkan (login/suara): suara
Memulai: Silahkan berbicara sekarang!
Selesai
The features of the files in the folder C:/Users/thosiba/speaker-recognition/data/recordings/train will be saved to train.csv
CSV Header: ['filename', 'chroma_stft', 'rmse', 'spectral_centroid', 'spectral_bandwidth', 'rolloff', 'zero_crossing_rate', 'mfcc1', 'mfcc2', 'mfcc3', 'mfcc4', 'mfcc5', 'mfcc6', 'mfcc7', 'mfcc8', 'mfcc9', 'mfcc10', 'mfcc11', 'mfcc12', 'mfcc13', 'mfcc14', 'mfcc15', 'mfcc16', 'mfcc17', 'mfcc18', 'mfcc19', 'mfcc20', 'label']
Traceback (most recent call last):
File "c:/Users/thosiba/speaker-recognition/login2.py", line 236, in <module>
access(option)
File "c:/Users/thosiba/speaker-recognition/login2.py", line 221, in access
suara()
File "c:/Users/thosiba/speaker-recognition/login2.py", line 79, in suara
extractWavFeatures("C:/Users/thosiba/speaker-recognition/data/recordings/train", TRAIN_CSV_FILE)
File "c:/Users/thosiba/speaker-recognition/login2.py", line 55, in extractWavFeatures
writer = csv.writer(file)
NameError: free variable 'csv' referenced before assignment in enclosing scope
我很确定它与调用函数或将其标记为全局函数有关,但我真的不明白在这种情况下如何解决它。很抱歉问了这么长的问题,因为我不知道如何解释得更好。
如果您在文件中的任何位置(甚至在错误行下方)命名变量 csv
,就会导致此错误。尝试将该变量的名称更改为其他名称。