【小甲鱼Python入门笔记】一个文件任务

【小甲鱼Python入门笔记】一个文件任务_第1张图片


算法实现如下

f = open("record2.txt")


#将读取到的每一行作为字符串存入一个list当中
boy = []
girl = []

#设置一个计数器 用于创建 三个文件名
count = 1


for each_line in f:
    
    if each_line[:6] != "======":
        # 当没遇到分割线时 将对话进行分割并保存
        
        #split(分割符,分割次数) 注意分隔符最好从文本中复制
        (name,talk) = each_line.split(":",1)
        if name == "小甲鱼":
            boy.append(talk)
        elif name == "小客服":
            girl.append(talk)
    else:
        #遇到分割线后,将对话存入不同的txt当中

        #初始化文件名 带上后缀
        boy_file_name = "boy" +str(count)+".txt"
        girl_file_name = "girl" +str(count) +".txt"

        #以可写入方式创建一个txt
        boy_file = open(boy_file_name,"w")
        girl_file = open(girl_file_name,"w")
        
        #按行写入txt文本中
        boy_file.writelines(boy)
        girl_file.writelines(girl)

        count=count +1
        boy= []
        girl = []

        
        #一定要注意写完后关闭文本!!!!
        boy_file.close()
        girl_file.close()

你可能感兴趣的:(笔记)