|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
代码跟答案差不多一样的,为什么调试总是出错,显示:
File "D:/Documents/Desktop/031课后练习动动手0.py", line 25, in <module>
(role, line_spoken) = each_line.split(':', 1)
TypeError: 'str' does not support the buffer interface
出错的这一段 (role, line_spoken) = each_line.split(':', 1),用029讲中的代码复制粘贴上去还是一样报错。
代码如下:
import pickle
def save_file(boy,girl,count):
boy_file = 'boy_' + count + '.txt'
girl_file = 'girl_' + count + '.txt'
f1 = open(boy_file, 'wb')
f2 = open(girl_file, 'wb')
pickle.dump(boy, f1)
pickle.dump(girl, f2)
f1.close()
f2.close()
f = open('record.txt','rb')
boy = []
girl = []
count = 1
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)
boy = []
girl = []
count += 1
save_file(boy,girl,count)
file.close()
你这个程序蛮多问题的
1.boy_file = 'boy_' + count + '.txt'
girl_file = 'girl_' + count + '.txt'
这里count是定义为int类型的,不能和字符串类型相加,应该为'boy'+str(count)+'.txt'
2.f = open('record.txt','rb')
这里不能使‘rb’打开方式,应该是'r'
3. (role, line_spoken) = each_line.split(':', 1)
那个‘:’,如果文件中的‘冒号’是使用输入法打上去的,这里也应该要对应用带有输入法的'冒号'
4.file.close()
这里'file'并没有定义,你有定义的是f,应该是f.close()
正确代码为:
- import pickle
- def save_file(boy,girl,count):
- boy_file = 'boy_' + str(count) + '.txt'
- girl_file = 'girl_' + str(count) + '.txt'
- f1 = open(boy_file, 'wb')
- f2 = open(girl_file, 'wb')
- pickle.dump(boy, f1)
- pickle.dump(girl, f2)
- f1.close()
- f2.close()
-
- f = open('record.txt','r')
- boy = []
- girl = []
- count = 1
- 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)
- boy = []
- girl = []
- count += 1
- save_file(boy,girl,count)
- f.close()
复制代码
|
|