第31讲里record保存男女的对话。希望大家帮我看看哪里出错了
f=open('record.txt')boy=[]
girl=[]
line=0
for eachline in f:
if eachline[:6]!='======':
if eachline[:3]=='小甲鱼':
eachline.lstrip('小甲鱼:')
line+=1
boy.append(eachline)
if eachline[:3]=='小客服':
eachline.lstrip('小客服:')
line+=1
girl.append(eachline)
boy_file=open('boy_*.txt','w')
boy_file.writelines(boy)
boy_file.close()
girl_file=open('girl_*.txt','w')
girl_file.writelines(girl)
girl_file.close()
f.close() 文件名不能包含 *
f=open('record.txt')
boy=[]
girl=[]
line=0
for eachline in f:
if eachline[:6]!='======':
if eachline[:3]=='小甲鱼':
eachline.lstrip('小甲鱼:')
line+=1
boy.append(eachline)
if eachline[:3]=='小客服':
eachline.lstrip('小客服:')
line+=1
girl.append(eachline)
boy_file=open('boy_.txt','w') # 把 * 去掉
boy_file.writelines(boy)
boy_file.close()
girl_file=open('girl_.txt','w') # 把 * 去掉
girl_file.writelines(girl)
girl_file.close()
f.close() 感谢回复,但是我的pythoncharm上显示还是不行,显示了这么一串Traceback (most recent call last):
File "C:\Users\vivi1\PycharmProjects\pythonProject1\main.py", line 5, in <module>
for eachline in f:
File "C:\Users\vivi1\AppData\Local\Programs\Python\Python310\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 2: character maps to <undefined>
不知道哪里出了问题 本帖最后由 isdkz 于 2022-2-18 23:31 编辑
cww_123 发表于 2022-2-18 23:12
感谢回复,但是我的pythoncharm上显示还是不行,显示了这么一串Traceback (most recent call last):
Fil ...
这是字符编码的问题,你打开record.txt文件的时候加个编码试试
f=open('record.txt', encoding='utf-8') # 改这一行,如果不行,把 utf-8 改成 gbk,一般都是这两个编码
boy=[]
girl=[]
line=0
for eachline in f:
if eachline[:6]!='======':
if eachline[:3]=='小甲鱼':
eachline.lstrip('小甲鱼:')
line+=1
boy.append(eachline)
if eachline[:3]=='小客服':
eachline.lstrip('小客服:')
line+=1
girl.append(eachline)
boy_file=open('boy_.txt','w') # 把 * 去掉
boy_file.writelines(boy)
boy_file.close()
girl_file=open('girl_.txt','w') # 把 * 去掉
girl_file.writelines(girl)
girl_file.close()
f.close()
页:
[1]