文件:一个任务
任务:将以下文件中的数据进行分割并按照以下规律保存:
- 你的对话单独保存为you_*.txt的文件(去掉you:)
- 我的对话单独保存为boy_*.txt的文件(去掉me:)
- 文件中总共有三段对话,分别保存为1/2/3共六个文件(文件中的对话使用“===”分割)
文件:
me:早安
you:早
me:在上班吗
you:嗯
===
me:在?
you:?
me:没什么,就是想聊聊天啦,你有空不
you:嗯
me:嗯嗯,xxxxxx(省略一万字)
me:?
me:算啦不聊了,你忙吧
===
me:待会儿打电话给你啦
you:不用了
me:为什么不用啊?
you:又没有什么要紧事,打什么电话
me:好多事情想告诉你啊
you:不用全部告诉我的
me:好吧,那不打扰了
实现代码:
凑合用版本:
file = open("test.txt")
girl = []
boy = []
count = 1
for each in file:
if each[:1] != "=":
# 字符串分割操作
(role, line_spoken) = each.split(":", 1)
if role == "you":
girl.append(line_spoken)
if role == "me":
boy.append(line_spoken)
else:
# 写入文件操作
file_name_girl = "girl_" + str(count) + ".txt"
file_name_boy = "boy_" + str(count) + ".txt"
girl_file = open(file_name_girl, "w")
boy_file = open(file_name_boy, "w")
girl_file.writelines(girl)
boy_file.writelines(boy)
girl_file.close()
boy_file.close()
print(girl)
print(boy)
girl = []
boy = []
count += 1
file.close()
面向对象版本:
def split_file(file_name):
file = open(file_name)
girl = []
boy = []
count = 1
for each in file:
if each[:1] != "=":
# 字符串分割操作
(role, line_spoken) = each.split(":", 1)
if role == "you":
girl.append(line_spoken)
if role == "me":
boy.append(line_spoken)
else:
save_file(boy, girl, count)
# 写入文件操作
girl = []
boy = []
count += 1
file.close()
def save_file(boy, girl, count):
file_name_girl = "girl_" + str(count) + ".txt"
file_name_boy = "boy_" + str(count) + ".txt"
girl_file = open(file_name_girl, "w")
boy_file = open(file_name_boy, "w")
girl_file.writelines(girl)
boy_file.writelines(boy)
girl_file.close()
boy_file.close()
print(girl)
print(boy)
split_file("test.txt")
相关文件:









网友评论