|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import pickle
pickle_file = open('record.txt','wb')
pickle.dump('record.txt',pickle_file)
boy = []
girl = []
count = 1
for each_line in pickle_file:
if each_line[:3] !='===':
(role,line_spoken) =each_line.split(':',1)
if role =='小甲鱼':
boy.append(line_spoken)
if role =='小客服':
girl.append(line_spoken)
else:
pickle_name_boy = 'boy_'+str(count)+'.txt'
pickle_name_girl = 'girl_'+str(count)+'.txt'
boy_pickle = open(pickle_name_boy,'wb')
girl_pickle = open(pickle_name_girl,'wb')
boy_pickle.dump(boy)
girl_pickle.dump(girl)
boy_pickle.close()
girl_pickle.close()
boy = []
girl = []
count +=1
pickle_name_boy = 'boy_'+str(count)+'.txt'
pickle_name_girl = 'girl_'+str(count)+'.txt'
boy_pickle = open(pickle_name_boy,'wb')
girl_pickle = open(pickle_name_girl,'wb')
boy_pickle.dump(boy)
girl_pickle.dump(girl)
boy_pickle.close()
girl_pickle.close()
pickle_file.close()
我还是用的之前的代码来写pickle储存,但是运行不了,有朋友帮我康康是什么问题吗?
本帖最后由 Twilight6 于 2020-7-13 10:48 编辑
[b]
第一个错误:pickle_file = open('record.txt','wb')
打开文件用 w 打开会把你文件直接覆盖了,你的 record.txt 文件运行一次就变空白了
第二个错误:pickle 模块用法错误
boy_pickle.dump(boy)、girl_pickle.dump(girl)等都要改成:pickle.dump(文件内容, 文件名)
第三个错误:
你用泡菜模块,后缀应该是 pkl 而不是 txt 吧
import pickle
pickle_file = open('record.txt').readlines()
boy = []
girl = []
count = 1
for each_line in pickle_file:
if each_line[:3] != '===':
(role, line_spoken) = each_line.split(':', 1)
if role == '小甲鱼':
boy.append(line_spoken)
if role == '小客服':
girl.append(line_spoken)
else:
pickle_name_boy = 'boy_' + str(count) + '.pkl'
pickle_name_girl = 'girl_' + str(count) + '.pkl'
boy_pickle = open(pickle_name_boy, 'wb')
girl_pickle = open(pickle_name_girl, 'wb')
pickle.dump(boy,boy_pickle)
pickle.dump(girl,girl_pickle)
boy_pickle.close()
girl_pickle.close()
boy = []
girl = []
count += 1
pickle_name_boy = 'boy_' + str(count) + '.pkl'
pickle_name_girl = 'girl_' + str(count) + '.pkl'
boy_pickle = open(pickle_name_boy, 'wb')
girl_pickle = open(pickle_name_girl, 'wb')
pickle.dump(boy,boy_pickle)
pickle.dump(girl,girl_pickle)
boy_pickle.close()
girl_pickle.close()
[/b]
|
|