|
发表于 2020-10-12 21:59:21
|
显示全部楼层
大概这样子吧,试试看
- f = open("test.txt",encoding = 'utf-8')
- boy = []
- girl = []
- count = 1
- for each_line in f:
- if each_line[:6] != '======':
- [a,b] = each_line.split(':',1)
- #返回的是切片的列表,1的意思相当于冒号出现的第一次切割开返回左右两个
- if a == '小甲鱼':
- boy.append(b)
- else:
- girl.append(b)
- #将话语加入对应序列
- else:
- file_name_boy = 'boy' + str(count) + '.txt'
- file_name_girl = 'girl' + str(count) + '.txt'
- # 命名规则
- file_boy = open(file_name_boy,'w')
- file_girl = open(file_name_girl,'w')
- #创建文件
- file_boy.writelines(boy)
- file_girl.writelines(girl)
- #把内容写入文件
- file_boy.close()
- file_girl.close()
- #关闭文件
- boy=[]
- girl=[]
- count += 1
- file_name_boy = 'boy' + str(count) + '.txt'
- file_name_girl = 'girl' + str(count) + '.txt'
- file_boy = open(file_name_boy,'w')
- file_girl = open(file_name_girl,'w')
- file_boy.writelines(boy)
- file_girl.writelines(girl)
- file_boy.close()
- file_girl.close()
- f.close
复制代码 |
|