8.1.6 一个任务
题目:将record.txt中的对话进行分割,并按照以下规则进行保存起来。
1.小甲鱼的对话单独保存为boy_*.txt的文件(去掉"小甲鱼:")
2.小客服的对话单独保存为girl_*.txt的文件(去掉"小客服:")
3.文章中有三段对话,分别保存为boy_1.txt、boy_2.txt、boy_3.txt、
girl_1.txt、girl_2.txt、girl_3.txt、共6个文件。(提示:每段对话用“===”隔开了)
******************* record.txt内容 ****************
小甲鱼:你好
小客服:你不好么,怎么这么问
小甲鱼:听说你有些忙,真的么
小客服:是啊,没有你忙碌
小甲鱼:我混日子的哦
小客服:我也一样
============================
小甲鱼:我说。。。
小客服:什么
小甲鱼:说不出来呢
小客服:害羞么
小甲鱼:不是
小客服:那就算了
=============================
小甲鱼:太阳从南北边出来咯
小客服:在讲梦话么,哥?
小甲鱼:别这么称呼我,不适应呢
小客服:旁边玩去,我很忙。
********************* record.txt内容 **************
---------------------常规思路如下所示---------------------------------------
boy=[]
girl=[]
count=1
f=open(r"C:\Users\Daodantou\Desktop\record.txt",encoding="UTF-8")
for eachline in f:
if eachline[:5]!="=====":
(mz,nr)=eachline.split(":",1)
if mz=="小甲鱼":
boy.append(nr)
if mz=="小客服":
girl.append(nr)
else:
fileNameBoy="C:\\Users\\Daodantou\\Desktop\\"+"boy_"+str(count)+".txt"
fileNameGirl = "C:\\Users\\Daodantou\\Desktop\\" + "girl_" + str(count) + ".txt"
boyfile=open(fileNameBoy,"w",encoding="UTF-8")
girlfile=open(fileNameGirl,"w",encoding="UTF-8")
boyfile.writelines(boy)
girlfile.writelines(girl)
count+=1
boy=[]
girl=[]
fileNameBoy="C:\\Users\\Daodantou\\Desktop\\"+"boy_"+str(count)+".txt"
fileNameGirl = "C:\\Users\\Daodantou\\Desktop\\" + "girl_" + str(count) + ".txt"
boyfile=open(fileNameBoy,"w",encoding="UTF-8")
girlfile=open(fileNameGirl,"w",encoding="UTF-8")
boyfile.writelines(boy)
girlfile.writelines(girl)
boyfile.close()
girlfile.close()
f.close()
---------------------代码封装 升级后 如下 ----------------------------------
def saveFile(boy,girl,count):
fileNameBoy = "C:\\Users\\Daodantou\\Desktop\\" + "boy_" + str(count) + ".txt"
fileNameGirl = "C:\\Users\\Daodantou\\Desktop\\" + "girl_" + str(count) + ".txt"
boyfile = open(fileNameBoy, "w", encoding="UTF-8")
girlfile = open(fileNameGirl, "w", encoding="UTF-8")
boyfile.writelines(boy)
girlfile.writelines(girl)
boyfile.close()
girlfile.close()
def splitFile(fileName):
girl = []
boy = []
count=1
f = open(fileName, encoding="UTF-8")
for eachline in f:
if eachline[:5] != "=====":
(mz, nr) = eachline.split(":", 1)
if mz == "小甲鱼":
boy.append(nr)
if mz == "小客服":
girl.append(nr)
else:
saveFile(boy,girl,count)
girl = []
boy = []
count += 1
saveFile(boy,girl,count)
f.close()
splitFile(r"C:\Users\Daodantou\Desktop\record.txt")
原文地址:https://www.cnblogs.com/daodantou/p/10352394.html