|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
原始版(有原始版才能很好的理解进化版,直接写进化版需要多多联系):
f = open('D:\\python\\experience\\record.txt')
boy = []
girl = []
count = 1
for eachline in f:
if eachline[ :6] != '======':
#进行字符串分割操作
(role,linespeak)= eachline.split(':',1)#难点 切片的使用和变量的赋值
if role == 'wgz':
boy.append(linespeak)
if role == 'zhou':
girl.append(linespeak)
else: #文件的分别保存操作
file_name_boy = 'boy' + str(count) + '.txt'
file_name_girl = 'girl' + str(count) +'.txt'
boy_file = open(file_name_boy,'w')
girl_file = open(file_name_girl,'w')
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
boy = []
girl = []
count += 1
file_name_boy = 'boy' + str(count) + '.txt'
file_name_girl = 'girl' + str(count) +'.txt'
boy_file = open(file_name_boy,'w')
girl_file = open(file_name_girl,'w')
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
f.close()
进化版:
def save_file(boy, girl, count):
file_name_boy = 'boy' + str(count) + '.txt'
file_name_girl = 'girl' + str(count) +'.txt'
boy_file = open(file_name_boy,'w')
girl_file = open(file_name_girl,'w')
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
def split_file(file_name):
f = open('D:\\python\\experience\\record.txt')# 需要完整路径 不知道小甲鱼为什么不需要
boy = []
girl = []
count = 1
for eachline in f: #变量名不能有空格
if eachline[ :6] != '======':
#进行字符串分割操作
(role,linespeak)= eachline.split(':',1)
if role == 'wgz':
boy.append(linespeak)
if role == 'zhou':
girl.append(linespeak)
else: #文件的分别保存操作
save_file(boy, girl, count)
boy = []
girl = []
count += 1 #加号和等号不能分开
save_file(boy, girl, count)
f.close()
split_file('D:\\python\\experience\\record.txt')
|
|