Pickle谈话内容(conversations)按角色(role)不同存入文本

将上课demo中的谈话内容(conversations)按角色(role)的不同,分别存入两个文本文件中

man = [] #分别定义两个list 用来存储两个role的conversations
other = []

try:
    data = open('sketch.txt')
    try:
        for each_line in data:
            (role, line_spoken) = each_line.split(':', 1)
            line_spoken = line_spoken.strip()
            if role == 'man': #通过判断role来确定要存入的list
                man.append(line_spoken)
            else:
                other.append(line_spoken)
    except ValueError:
        pass
    data.close() #别忘了完成文件操作关闭数据文件对象
except IOError:
    print('The file is missing!')

try:
    man_file = open('man_data.txt', 'w') #数据文件对象中的文件参数如果不存在,并且相应目录有相应权限,open()会自动创建文件
    other_file = open('other_data.txt', 'w') # 'w'为文件数据对象的'写'模式

    print(man, file = man_file) #print()函数中的file参数为写入的文件名
    print(other, file = other_file)

    man_file.close() #别忘了完成文件操作关闭数据文件对象
    other_file.close()
except IOError:
    print('File Error!')

随后,这个问题被加深了难度,见网址:
http://bbs.fishc.com/forum.php?mod=viewthread&tid=45890&extra=page%3D1%26filter%3Dtypeid%26typeid%3D398

# -*- coding: utf-8 -*-
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")
    girl_file=open(file_name_girl,"wb")

    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=[]

    file_read=open(file_name,"r")
    for each_line in file_read.readlines():
        if each_line[:6] != "======":
            print(each_line.split(":", 1))
            (role,line_spoken)=each_line.split(":",1)
            line_spoken=line_spoken.strip()
            if role=="小甲鱼":
                boy.append(line_spoken)
            if role=="小客服":
                girl.append(line_spoken)
        else:
            save_file(boy,girl,count)
            boy=[]
            girl=[]
            count+=1

    file_read.close()


split_file("record.txt")

注:
有人出现这个问题:
Traceback (most recent call last):
File “C:\Users\Administrator\Desktop\s.py”, line 7, in
role, line_spoken = line.split(“:”, maxsplit=1)
ValueError: not enough values to unpack (expected 2, got 1)

原因:record.txt文件中“:”是中文的冒号,split(“:”,1)和record.txt中冒号要统一。

我当时错在了这行:

if each_line[:6] != "======":

漏掉了[:6],导致程序运行到“===========”,没有冒号,无法split。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值