1、样本内容 A.txt
2、上代码:
f=open(r'E:\A.txt','r') boyA=[]
boyB=[]
count = for each_line in f:
if each_line[:]!='======':
(role,line_spoken)=each_line.split(':',)
print((role,line_spoken))
if role == 'A':
boyA.append(line_spoken)
if role =='B':
boyB.append(line_spoken)
else:
file_name_boyA = r'E:\boyA_'+str(count)+'.txt'
file_name_boyB = r'E:\boyB_' + str(count) + '.txt' boyA_file = open(file_name_boyA,'w')
boyB_file = open(file_name_boyB, 'w') boyA_file.writelines(boyA)
boyB_file.writelines(boyB) boyA_file.close()
boyB_file.close() boyA = []
boyB = []
count += file_name_boyA = r'E:\boyA_' + str(count) + '.txt'
file_name_boyB = r'E:\boyB_' + str(count) + '.txt' boyA_file = open(file_name_boyA,'w')
boyB_file = open(file_name_boyB, 'w') boyA_file.writelines(boyA)
boyB_file.writelines(boyB) boyA_file.close()
boyB_file.close() f.close()
3、上结果:
4、代码优化一下
#第二个函数
def save_file(boyA,boyB,count):
file_name_boyA = r'E:\boyA_' + str(count) + '.txt'
file_name_boyB = r'E:\boyB_' + str(count) + '.txt' boyA_file = open(file_name_boyA, 'w')
boyB_file = open(file_name_boyB, 'w') boyA_file.writelines(boyA)
boyB_file.writelines(boyB) boyA_file.close()
boyB_file.close() #第一个函数
def split_file(file_name):
f=open(file_name,'r') boyA = []
boyB = []
count =
for each_line in f:
if each_line[:]!='======':
(role,line_spoken)=each_line.split(':',)
print((role,line_spoken))
if role == 'A':
boyA.append(line_spoken)
if role =='B':
boyB.append(line_spoken)
else:
save_file(boyA, boyB, count) boyA = []
boyB = []
count += save_file(boyA,boyB,count) f.close() # 调用
split_file(r'E:\A.txt')