|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
程序1:
fff=open("E:\\python\\课件资料\\record.txt","rt")
num=1
boy=[]
girl=[]
for each in fff :
boy_file_name="boy_"+str(num)+".txt"
girl_file_name="girl_"+str(num)+".txt"
if each[:3] !="===":
txt=each.split(":")
if txt[0]=="小甲鱼":
boy.append(txt[1])
elif txt[0]=="小客服":
girl.append(txt[1])
else:
boy_file=open("E:\\python\\课件资料\\"+boy_file_name,"at")
girl_file=open("E:\\python\\课件资料\\"+girl_file_name,"at")
boy_file.writelines(boy)
girl_file.writelines(girl)
boy=[]
girl=[]
num+=1
boy_file=open("E:\\python\\课件资料\\"+boy_file_name,"at")
girl_file=open("E:\\python\\课件资料\\"+girl_file_name,"at")
boy_file.writelines(boy)
girl_file.writelines(girl)
fff.close()
boy_file.close()
girl_file.close()
程序2:
fff=open("E:\\python\\课件资料\\record.txt","rt")
num=1
boy=[]
girl=[]
for each in fff :
boy_file_name="boy_"+str(num)+".txt"
girl_file_name="girl_"+str(num)+".txt"
if each[:3] !="===":
txt=each.split(":")
if txt[0]=="小甲鱼":
boy.append(txt[1])
elif txt[0]=="小客服":
girl.append(txt[1])
else:
boy_file=open("E:\\python\\课件资料\\"+boy_file_name,"at")
girl_file=open("E:\\python\\课件资料\\"+girl_file_name,"at")
boy_file.writelines(boy)
girl_file.writelines(girl)
boy=[]
girl=[]
num+=1
boy_file=open("E:\\python\\课件资料\\"+boy_file_name,"at")
girl_file=open("E:\\python\\课件资料\\"+girl_file_name,"at")
boy_file.writelines(boy)
girl_file.writelines(girl)
fff.close()
boy_file.close()
girl_file.close()
注意以下两种情况的比较:
else:
boy_file=open("E:\\python\\课件资料\"+boy_file_name,"at")
girl_file=open("E:\\python\\课件资料\"+girl_file_name,"at")
boy_file.writelines(boy)
girl_file.writelines(girl)
boy=[]
girl=[]
num+=1
else:
boy_file=open("E:\\python\\课件资料\"+boy_file_name,"at")
girl_file=open("E:\\python\\课件资料\"+girl_file_name,"at")
boy_file.writelines(boy)
girl_file.writelines(girl)
boy=[]
girl=[]
num+=1
区别在于,列表清空是在else里还是在else外
观察代码不难发现,在for循环内
if判断遇到‘===’后,分割隔断内容,将各自对话去除角色添加在各自的列表里
else则是对应 将各自列表里的东西写入各自文件,写完后清空列表,等待下次循环时新建一对txt文件,重新读取对话,存入列表,并写入
也就是意味着,列表的清空必须紧跟写入 boy_file.writelines(boy)
girl_file.writelines(girl)
假设你放在外面(与else缩进平齐),也就意味着,每执行一次循环都会清空一次
如果这次循环中,没有执行else,而只是执行了if,,刚刚append进去的内容,不等写入文件,就都没了
这好吗?这不好!
|
|