一、例子如下:一段对话通过:进行分割,分别存储到不同的文件,文件名字为:record.txt
参考链接:http://www.runoob.com/python/att-string-split.html
郝奥伟:你是谁?
王甜甜:弄啥呢?你在干嘛?????
王甜甜:what are You doing??
郝奥伟:我在操场打篮球????
==================================
郝奥伟:你是谁吗?
王甜甜:今天天气真好????
王甜甜:可以出去逛逛
郝奥伟:准备去天安门
郝奥伟:到故宫去玩
==================================
郝奥伟:你是谁吗?
王甜甜:今天天气真好????
王甜甜:可以出去逛逛
郝奥伟:准备去天安门
郝奥伟:到故宫去玩
==================================
二、执行python如下:
f = open('record.txt') #打开文件
boy = []
girl = []
count =1
for each_line in f:
#完成分段切割 依据是'===='
print(each_line)
if each_line[:6] != '======':
#这里容易出错,注意冒号为英文
(role,line_spoken) = each_line.split(':',1)
if role == '郝奥伟':
boy.append(line_spoken)
if role == '王甜甜':
girl.append(line_spoken)
else:
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()
boy = []
girl = []
count +=1
f.close()
三、对python程序进行优化:
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 split_file(file_name):
f = open(file_name) #打开文件
boy = []
girl = []
count =1
for each_line in f:
#完成分段切割 依据是'===='
print(each_line)
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
f.close()
split_file('record.txt')
四:得到的输出结果为: