|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import pickle
def save_file(boy, girl, count):
file_name_boy = 'boy_' + str(count) + '.txt'
file_name_girl = 'girl_' + str(count) + '.txt'
boy_file = open(file_name_boy, 'wb') # 记得一定要加 b 吖
girl_file = open(file_name_girl, 'wb') # 记得一定要加 b 吖
pickle.dump(boy, boy_file)
pickle.dump(girl, girl_file)
boy_file.close()
girl_file.close()
def split_file(file_name):
count = 1
boy = []
girl = []
f = open(file_name)
for each_line in f:
if each_line[:6] != '======':
(role, line_spoken) = each_line.split(':', 1)
if role == '小甲鱼':
boy.append(line_spoken)
if role == '小客服':
girl.append(line_spoken)
else:
save_file(boy, girl, count)
boy = []
girl = []
count += 1
save_file(boy, girl, count)
f.close()
split_file('record.txt')
可以看看注释 - #定义写入函数
- def save_file(boy,girl,count): #传入两个列表(用于存储对话内容)和一个计数器
- file_name_boy='boy_'+str(count)+'.txt' #新建一系列文件,命名由字符串拼接
- file_name_girl='girl_'+str(count)+'.txt'#同理
-
- boy_file=open(file_name_boy,'w') #以写入方式打开
- girl_file=open(file_name_girl,'w') #同理
-
- boy_file.writelines(boy) #写入
- girl_file.writelines(girl)
-
- boy_file.close() #关闭
- girl_file.close()
-
- #定义切分函数
- def spilt_file(file_name): #传入文件名
- f = open(file_name,"r",encoding='UTF-8')
- #关键点,编码方式 就这里换个编码形式
- boy=[]
- girl=[]
- count=1
-
- for each_line in f: #遍历原对话文件每一行
- if each_line[:6]!='======': #以分割线判断
- (role,line_spoken)=each_line.split(':',1)
- #以:为界,分成元组,进行1次操作
- if role =='小甲鱼': #根据名称(前三个字符)不同分别记入两个列表
- boy.append(line_spoken)
- if role =='小客服':
- girl.append(line_spoken)
- #到这一步,所有对话均被存入两列表
- else: #不是分割线的情况下,写入
- save_file(boy,girl,count) #调用写入,写入后清空列表,等待下次添加对话内容
-
- boy=[]
- girl=[]
- count+=1 #count从2到3时跳出循环,所以文件里计数器count为3的那一对文件就缺少了
-
- save_file(boy,girl,count) #第三段内容(上方for循环漏掉一次写入)
- f.close()
-
- spilt_file('record.txt')
复制代码
|
-
|