实验5 文件应用编程
task3.py
1 with open('data3.txt','r+', encoding='UTF-8') as f: 2 Z=[] 3 Y=[] 4 x=[] 5 for i in f: 6 x.append(i.strip('\n')) 7 newx=x[1:11] 8 for i in newx: 9 y=float(i) 10 Y.append(y) 11 if y-int(y) >= 0.5: 12 y=int(y)+1 13 else: 14 y=int(y) 15 Z.append(y) 16 print(f'原始数据\n{Y}') 17 print(f'四舍五入后的数据\n{Z}') 18 19 with open('data3_processed.txt','w',encoding='utf-8') as f: 20 write1=['原始数据']+Y 21 write2=['四舍五入后的数据']+Z 22 for i in range (len(Y)): 23 f.write(f'{write1[i]}\t{write2[i]}\n')
task4.py
1 with open('data4.txt', 'r', encoding = 'utf-8') as f: 2 Y=[] 3 l=[] 4 t=[] 5 e=[] 6 data=f.readlines() 7 for i in data: 8 i=i.split() 9 Y.append(i) 10 Y.remove(Y[0]) 11 newlist1=sorted(Y,key=(lambda x : x[2])) 12 for i in range (0,8): 13 l.append(newlist1[i]) 14 l1=sorted(l,key=(lambda x : x[3]),reverse=True) 15 for i in range (8,10): 16 t.append(newlist1[i]) 17 l2=sorted(t,key=(lambda x : x[3]),reverse=True) 18 X=l1+l2 19 for i in X: 20 i1='\t'.join(i) 21 i1=i1+'\n' 22 e.append(i1) 23 e.insert(0,'学号\t姓名\t专业\t分数\n') 24 for i in e: 25 print(i) 26 with open('data4_processed.txt','w',encoding='utf-8') as f: 27 for i in e: 28 f.write(i)
task5.py
1 with open('data5.txt', 'r+', encoding = 'utf-8') as f: 2 data=f.read() 3 print('行数',len(data.splitlines())) 4 print('单词数',len(data.split())) 5 s=0 6 for i in data: 7 if i.isspace(): 8 s=s+1 9 print('空格数',s) 10 print('字符数',len(data)) 11 12 13 with open('data5_with_line.txt', 'w+', encoding = 'utf-8') as f: 14 for i in range(len(data.splitlines())): 15 f.write(str(i+1)+' '+str(data.splitlines()[i])+'\n')