最近在看小甲鱼的视频,把写的文件切割代码拿出来捋捋

#-*- coding:utf-8 -*-
f = open('foo.txt')

man = [] #定义两个空列表
women =[]
count = 1 #初始化计数器

for each_line in f:
    if each_line[:6] != '======': #如果文档未遇到分隔符,则切割
        (role,line_spoken) = each_line.split(':',1)#遇到冒号则切割1次
        if role == 'boy':
            man.append(line_spoken) #将角色boy的话添加到man列表
        if role == 'girl':
            women.append(line_spoken)
    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(man)#将列表内容分别写入文件
        girl_file.writelines(women)
        
        boy_file.close()
        girl_file.close()
        
        man = []
        women = []
        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(man)
girl_file.writelines(women)
        
boy_file.close()
girl_file.close()

f.close()
        

升级版代码捋捋

#-*- coding:utf-8 -*-

#自定义保存文件函数 def save_file(man, women, 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(man) girl_file.writelines(women) boy_file.close() girl_file.close() #自定义分割文件函数 def fenge(filename): f = open(filename) man = [] women =[] count = 1 for each_line in f: if each_line[:6] != '======': (role,line_spoken) = each_line.split(':', 1) if role == 'boy': man.append(line_spoken) if role == 'girl': women.append(line_spoken) else: save_file(man, women, count) man = [] women = [] count += 1 save_file(man, women, count) f.close() fenge('foo.txt')

 

END!

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-17
  • 2021-11-30
  • 2022-12-23
  • 2021-12-15
猜你喜欢
  • 2021-07-01
  • 2021-09-07
  • 2022-01-18
  • 2022-02-09
  • 2022-01-18
  • 2021-12-24
  • 2021-07-24
相关资源
相似解决方案