关闭

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

标签: python
82人阅读 评论(0) 收藏 举报
分类:

将上课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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:20319次
    • 积分:495
    • 等级:
    • 排名:千里之外
    • 原创:28篇
    • 转载:10篇
    • 译文:0篇
    • 评论:2条
    文章分类
    文章存档
    最新评论