文件颜值
大佬们,为什么会这样报错啊? a=open('record (3).txt')x=1
def han():
global x
x=str(x)
q=open('boy_'+x+'.txt','w')
w=open('girl_'+x+'.txt','w')
for i in a:
b=a.readline()
if '小甲鱼' in i:
a.replace('小甲鱼:','')
q.write(b)
elif '小客服' in i:
a.replace('小客服:','')
w.write(b)
elif "==========" in i:
x=int(x)
x=x+1
han()
break
han() 正天圣人 发表于 2021-6-9 21:07
a=open('record (3).txt')
x=1
def han():
你不能对文件对象进行 replace 呀,这是字符串的方法
还要 replace 不是在原对象上进行修改的,你对一个字符串执行了 replace 需要那一个变量来接收替换后的字符串
正天圣人 发表于 2021-6-9 21:07
a=open('record (3).txt')
x=1
def han():
认真看了下你的代码,还有 for 循环 a 文件对象了,那么文件每次循环都会向下移动一行
但是你还在 for 循环中加了 a.readline() 导致每次 for 循环 文件指针移动两行
而你还进行了递归,肯定会导致有些递归读取到的是空文件,因为你每次读取的文件对象都是同一个,而且最后文件指针会移动到文本末尾了
帮你改了下代码,参考下吧:
a = open('record.txt', encoding='utf-8')
x = 1
def han():
global x
q = open('boy_%d.txt' % x, 'w', encoding='utf-8')
w = open('girl_%d.txt' % x, 'w', encoding='utf-8')
for i in a:
if '小甲鱼' in i:
b = i.replace('小甲鱼:', '')
q.write(b)
elif '小客服' in i:
b = i.replace('小客服:', '')
w.write(b)
elif "=======" in i:
x = x + 1
han()
han() Twilight6 发表于 2021-6-9 21:43
认真看了下你的代码,还有 for 循环 a 文件对象了,那么文件每次循环都会向下移动一行
但是你还 ...
大佬,我把改成这样了
a=open('record (3).txt')
x=1
def han():
global x
x=str(x)
q=open('boy_'+x+'.txt','w')
w=open('girl_'+x+'.txt','w')
for i in a:
if '小甲鱼' in i:
i.replace('小甲鱼:','')
q.write(i)
elif '小客服' in i:
i.replace('小客服:','')
w.write(i)
elif "==========" in i:
x=int(x)
x=x+1
han()
han() Twilight6 发表于 2021-6-9 21:43
认真看了下你的代码,还有 for 循环 a 文件对象了,那么文件每次循环都会向下移动一行
但是你还 ...
可是,第一行为什么是小客服? Twilight6 发表于 2021-6-9 21:43
认真看了下你的代码,还有 for 循环 a 文件对象了,那么文件每次循环都会向下移动一行
但是你还 ...
建议用split()对 聊天对话 进行分割
举例:
小客服:小甲鱼, 今天有客户问你有没有女朋友
你的代码会把这句话保存到boy_1.txt中
但这明显是不符合项目需求的
用split()分割后,只判断左边的对话人物就可以了 正天圣人 发表于 2021-6-9 22:06
可是,第一行为什么是小客服?
那么你就像甲鱼哥那样用 split 即可
或者用切片,参考代码:
a = open('record.txt', encoding='utf-8')
x = 1
def han():
global x
q = open('boy_%d.txt' % x, 'w', encoding='utf-8')
w = open('girl_%d.txt' % x, 'w', encoding='utf-8')
for i in a:
if '小甲鱼' in i[:3]:
q.write(i)
elif '小客服' in i[:3]:
w.write(i)
elif "=======" in i:
x = x + 1
han()
han()
你这里的 replace 没意义,原因看前几楼的说明
Twilight6 发表于 2021-6-9 23:09
那么你就像甲鱼哥那样用 split 即可
或者用切片,参考代码:
大佬,我把改成这样了,可是为什么第一句话还是小客服啊?
a=open('record (3).txt')
x=1
def han():
global x
x=str(x)
q=open('boy_'+x+'.txt','w')
w=open('girl_'+x+'.txt','w')
for i in a:
if '小甲鱼' in i:
(wu,k)=i.split(':',1)
q.write(k)
elif '小客服' in i:
(wu,k)=i.split(':',1)
w.write(k)
elif "==========" in i:
x=int(x)
x=x+1
han()
han()
而且,关于replace是不是因为只能操作字符串,而这里的i不是字符串,所以用不了啊? 正天圣人 发表于 2021-6-10 16:08
大佬,我把改成这样了,可是为什么第一句话还是小客服啊?
a=open('record (3).txt')
x=1
a=open('record.txt')
x=1
def han():
global x
x=str(x)
q=open('boy_'+x+'.txt','w')
w=open('girl_'+x+'.txt','w')
for i in a:
if "==========" in i:
x=int(x)
x=x+1
han()
else:
(wu, k) = i.split(':', 1)
if '小甲鱼' == wu:
q.write(k)
elif '小客服' == wu:
w.write(k)
han() Twilight6 发表于 2021-6-10 16:41
谢谢大佬,我知道我错在哪里了!
页:
[1]