荀命不保 发表于 2020-8-20 11:41:40

第二十九讲,

问题1:标红的( (role,line_spoken) = each_line.split(':',1))怎么理解。
问题2:运行代码,没生成(boy_' + str(count)+'.txt之类文件)


boy =[]
girl =[]
count = 0
f=open('D:\\record2.txt')
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=[]
          girl=[]
          count +=1

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()
boy_file.close()
f.close()



Twilight6 发表于 2020-8-20 11:45:37



你忘记关闭文件了在循环中,而且最后的关闭文件错了重复关闭 boy 的文件了

boy =[]
girl =[]
count = 0
f=open('D:\\record2.txt')
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

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()
f.close()

荀命不保 发表于 2020-8-20 16:40:27

最后忘记关闭girl_file.close() 文件
页: [1]
查看完整版本: 第二十九讲,