1. 程式人生 > >第八章 永久存儲[DDT書本學習 小甲魚]【2】

第八章 永久存儲[DDT書本學習 小甲魚]【2】

沒有 lena encoding 代碼 你好 enc lse odi .com

技術分享圖片

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")

第八章 永久存儲[DDT書本學習 小甲魚]【2】