森亦简 发表于 2022-6-3 15:46:26

课后作业31讲:用pickle将文件里的对话按照以下要求腌制成不同文件

本帖最后由 森亦简 于 2022-6-3 15:52 编辑

按照课上的代码,不知道为啥会报错,求解惑
报错内容:

Traceback (most recent call last):
File "C:/Users/wxl0311/Desktop/新建文件夹/221.py", line 22, in <module>
    (role,line_spoken) = each_line.split(":",1)
ValueError: not enough values to unpack (expected 2, got 1)

Traceback (most recent call last):
File "C:/Users/wxl0311/Desktop/新建文件夹/221.py", line 22, in <module>
    (role,line_spoken) = each_line.split(sep=":",maxsplit=1)
ValueError: not enough values to unpack (expected 2, got 1)

我的代码:报错在第22行
def save_file(boy,girl,count):
    import pickle
    boy_file_name = "boy_" + str(count) + ".txt"
    girl_file_name = "girl_" + str(count) + ".txt"
   
    boy_file = open(boy_file_name,"wb")
    girl_file = open(girl_file_name,"wb")
   
    pickle.dump(boy,boy_file)
    pickle.dump(girl,girl_file)
   
    boy_file.close()
    girl_file.close()
   
f = open("record.txt")
count = 1
boy = []
girl = []

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)

      count = 1
      boy = []
      girl = []
      
save_file(boy,girl,count)
f.close()

Twilight6 发表于 2022-6-3 16:14:59


if each_line[:6] != "=====": 这行代码 等号少一个,导致 if 必成立

而当全是等号那行文本时,没有冒号 split 切割只会返回一个元素,但你需要赋值给两个变量而报错

def save_file(boy,girl,count):
    import pickle
    boy_file_name = "boy_" + str(count) + ".txt"
    girl_file_name = "girl_" + str(count) + ".txt"
   
    boy_file = open(boy_file_name,"wb")
    girl_file = open(girl_file_name,"wb")
   
    pickle.dump(boy,boy_file)
    pickle.dump(girl,girl_file)
   
    boy_file.close()
    girl_file.close()
   
f = open("record.txt")
count = 1
boy = []
girl = []

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)

      count = 1
      boy = []
      girl = []
      
save_file(boy,girl,count)
f.close()

森亦简 发表于 2022-6-3 16:42:33

额,大意了太粗心了,谢谢大佬!!{:10_254:}

AlexTao 发表于 2022-6-3 21:36:46

牛人。
页: [1]
查看完整版本: 课后作业31讲:用pickle将文件里的对话按照以下要求腌制成不同文件