|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
这是我写的代码:
f = open('record.txt')
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:
file_name_boy = 'boy_' + str(count) + '.txt'
file_name_girl = 'girl_' + str(count) + '.txt'
boy_file = open(file_name_boy,'w')
girl_file = open(file_name_girl,'w')
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
boy = []
girl = []
count += 1
f.close()
然后执行后有错误!
错误是:
Traceback (most recent call last):
File "C:\Users\dell\Documents\test_1.py", line 11, in <module>
(role,line_spoken) = each_line.split(':',1)
ValueError: not enough values to unpack (expected 2, got 1)
学霸看看这是咋回事!
本帖最后由 醉酒青牛 于 2017-9-20 11:08 编辑
这是我写的代码,经测试无误。如果你还是找不到原因,你的代码可以放上来,我帮你调试一下。
- f = open('record.txt','rt') #以只读方式打开record.txt文档
- boy = [] #存放小甲鱼的内容
- girl = [] #存放小客服的内容
- count = 1 #计数一共多少段内容
- for each_line in f: #读取文档内每一行字符串
- if each_line[:5] != '=====': #当提取字符串内容的前5个字符不等于'=====',分割字符串并保存到对应列表内
- (role,line_spoken) = each_line.split(':',1)
- if role == '小甲鱼':
- boy.append(line_spoken)
- else:
- girl.append(line_spoken)
- else: #相等则将当前列表内的内容保存到相应文件内
- file_boy_name = '%s%c%d.txt' %('小甲鱼','_',count)
- file_girl_name = '%s%c%d.txt' %('小客服','_',count)
- f1 = open(file_boy_name,'xt')
- f1.writelines(boy)
- f2 = open(file_girl_name,'xt')
- f2.writelines(girl)
- boy = []
- girl = []
- f1.close()
- f2.close()
- count += 1
- file_boy_name = '%s%c%d.txt' %('小甲鱼','-',count) #将第三段内容保存到各自文档内
- file_girl_name = '%s%c%d.txt' %('小客服','-',count)
- f1 = open(file_boy_name,'xt')
- f1.writelines(boy)
- f2 = open(file_girl_name,'xt')
- f2.writelines(girl)
- boy = []
- girl = []
- f1.close()
- f2.close()
- f.close() #关闭刚开始打开的record.txt文件
复制代码
|
|