第7行if each_line != "============":
总是成立的,因为each_line代表一整行,但是没有哪一行是等于12个字符的"============",也就是不管有没有":"号都会执行分割,导致第9行在以:号分割================================================================================的时候分割出来只有一个值,没有足够的结果赋值给role,line_spoken两个变量,所以报错。
改成这样就可以了,不过你的代码还有其他逻辑问题,应该不能实现你想要的结果f = open("E:\\推土机\\课后答案\\record.txt")
boy = []
girl = []
count = 1
for each_line in f:
if each_line[:12] != "============":
# 字符串分隔
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(
"E:\\推土机\\课后答案\\第29讲:文件:一个任务 课后测试题及答案\\file_name_boy", "w"
)
girl_file = open(
"E:\\推土机\\课后答案\\第29讲:文件:一个任务 课后测试题及答案\\file_name_girl", "w"
)
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
boy = []
girl = []
count += 1
file_name_boy = "boy_" + str(count) + ".txt"
file_name_girl = "girl_" + str(count) + ".txt"
boy_file = open("E:\\推土机\\课后答案\\第29讲:文件:一个任务 课后测试题及答案\\file_name_boy", "w")
girl_file = open("E:\\推土机\\课后答案\\第29讲:文件:一个任务 课后测试题及答案\\file_name_girl", "w")
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
f.close()
|