【Python學習筆記Day29】 文件——一個任務
任務:將文件(record.txt)中的數據進行分割並按照以下規律保存起來
record.txt:
小客服:小甲魚,今天有客戶問你有沒有女朋友?
小甲魚:咦??
小客服:我跟她說你有女朋友了!
小甲魚:。。。。。。
小客服:她讓你分手後考慮下她!然後我說:"您要買個優盤,我就幫您留意下~"
小甲魚:然後呢?
小客服:她買了兩個,說發一個貨就好~
小甲魚:呃。。。。。。你真牛!
小客服:那是,誰讓我是魚C最可愛小客服嘛~
小甲魚:下次有人想調戲你我不阻止~
小客服:滾!!!
================================================================================
小客服:小甲魚,有個好評很好笑哈。
小甲魚:哦?
小客服:"有了小甲魚,以後媽媽再也不用擔心我的學習了~"
小甲魚:哈哈哈,我看到丫,我還發微博了呢~
小客服:嗯嗯,我看了你的微博丫~
小甲魚:喲西~
小客服:那個有條回覆“左手拿著小甲魚,右手拿著打火機,哪裡不會點哪裡,so easy ^_^”
小甲魚:T_T
================================================================================
小客服:小甲魚,今天一個會員想找你
小甲魚:哦?什麼事?
小客服:他說你一個學生月薪已經超過12k了!!
小甲魚:哪裏的?
小客服:上海的
小甲魚:那正常,哪家公司?
小客服:他沒說呀。
小甲魚:哦
小客服:老大,爲什麼我工資那麼低啊??是時候漲漲工資了!!
小甲魚:啊,你說什麼?我在外邊呢,這裏好吵吖。。。。。。
小客服:滾!!!
1)小甲魚的對話單獨保存爲boy_.txt文件(去掉“小甲魚:”)
2)小客服的對話單獨保存爲girl_.txt的文件(去掉小客服:)
3)文件中總共有三段對話,分別保存爲boy_1.txt,girl_1.txt,boy_2.txt,girl_2.txt,boy_3.txt,girl_3.txt
共6個文件(文件中不同的對話間已經使用“======”分割)
f = open('record.txt',encoding='utf-8')
print(f.read())
f.close()
f = open('record.txt',encoding='utf-8')
boy = []
girl = []
count = 1
for each_line in f:
if str(each_line[:6]) != "======":
(name,content) = each_line.split(':',1) #https://www.cnblogs.com/jsdd/p/11613121.html
if name == "小甲魚":
boy.append(content)
else:
girl.append(content)
else:
file_boy_name = "boy_" + str(count) + ".txt"
file_girl_name = "girl_" + str(count) + ".txt" #文件名
boy_file = open(file_boy_name,'w')
girl_file = open(file_girl_name,'w') #以打開方式創建文件,不存在創建,存在覆蓋
boy_file.writelines(boy)
girl_file.writelines(girl) #將每一行寫入列表裏
boy_file.close()
girl_file.close() #關閉文件
boy = []
girl = [] #每次初始化列表
count += 1 #計數加一
file_boy_name = "boy_" + str(count) + ".txt"
file_girl_name = "girl_" + str(count) + ".txt"
boy_file = open(file_boy_name,'w')
girl_file = open(file_girl_name,'w')
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
f.close()
用函數優化程序,把經常出現的用函數封裝
def div(count,boy,girl):
file_boy_name = "boy_" + str(count) + ".txt"
file_girl_name = "girl_" + str(count) + ".txt"
boy_file = open(file_boy_name,'w')
girl_file = open(file_girl_name,'w')
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
"""
f = open('record.txt',encoding='utf-8')
boy = []
girl = []
count = 1
for each_line in f:
if str(each_line[:6]) != "======":
(name,content) = each_line.split(':',1) #https://www.cnblogs.com/jsdd/p/11613121.html
if name == "小甲魚":
boy.append(content)
else:
girl.append(content)
else:
div(count,boy,girl)
count += 1
boy = []
girl = []
div(count,boy,girl)
f.close()
"""
可以繼續對該程序進程封裝:
def split_file(file_name):
f = open(file_name,encoding='utf-8')
boy = []
girl = []
count = 1
for each_line in f:
if str(each_line[:6]) != "======":
(name,content) = each_line.split(':',1) #https://www.cnblogs.com/jsdd/p/11613121.html
if name == "小甲魚":
boy.append(content)
else:
girl.append(content)
else:
div(count,boy,girl)
count += 1
boy = []
girl = []
div(count,boy,girl)
f.close()
split_file('record.txt')