关于函数变量位置的问题
import pickleboy = [] ##这些变量设置在这里,这样就会报错 说没有定义boy和girl??在split_text下面定义就不会报错,这是怎么回事??这不是全局变量吗 哪里都可以使用??
girl = []
count = 0
file_name = r'C:\Users\lwg\Desktop\OBS报名\anything.txt'
##boy girl 这些变量可以被访问
def split_text(file_name):
f = open(file_name,encoding = 'utf-8')
for each_line in f:
if each_line[:6] != '======':
(role,spoken) = each_line.split(':',1)
if role == '小甲鱼':
boy.append(spoken)
if role == '小客服':
girl.append(spoken)
else:
save_file(boy,girl,count)
boy = []##
girl = []
save_file(boy,girl,count)
f.close()
def save_file(boy,girl,count):
count += 1
file_name_boy = '爷们'+ str(count) + '.txt'
file_name_girl = '娘们' + str(count) + '.txt'
boy_file = open(file_name_boy,'wb')
girl_file = open(file_name_girl,'wb')
pickle.dump(boy,boy_file)
pickle.dump(girl,girl_file)
boy_file.close()
girl_file.close()
实测没有问题 你说反了吧 全局变量
boy=[]
girl=[]
局部变量也有
else:
save_file(boy,girl,count)
boy = []##
girl = []
默认使用局部变量
UnboundLocalError: local variable 'girl' referenced before assignment
>>> boy = []
>>> def b():
boy.append('ilovefishc')
boy = []
>>> b()
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
b()
File "<pyshell#4>", line 2, in b
boy.append('ilovefishc')
UnboundLocalError: local variable 'boy' referenced before assignment
UnboundLocalError:分配前已引用局部变量“ boy”
这里修改的话,要么boy,gir属于split_text(file_name)的局部变量
要么在split_text(file_name)中声明全局变量
页:
[1]