实验五

task3
1
with open('data3.txt','r',encoding='utf-8') as f: 2 data=f.readlines() 3 f.close() 4 with open('data3_processed.txt','w',encoding='utf-8') as b: 5 a=['四舍五入后数据:'] 6 for i in range(len(data)): 7 data[i]=data[i].strip('\n') 8 for i in data[1:]: 9 i=eval(i) 10 if i-int(i)<0.5: 11 a.append(str(int(i))) 12 else: 13 a.append(str(int(i)+1)) 14 for i in range(len(data)): 15 b.write(data[i]+'\t'+a[i]+'\n') 16 b.close() 17 a1=[];a2=[] 18 for i in range(1,len(data)): 19 a1.append(eval(data[i])) 20 a2.append(int(a[i])) 21 print(f'原始数据:\n{a1}\n四舍五入后数据:\n{a2}')

 

 task4

 1 f=open('data4.txt','r',encoding='utf-8')
 2 a=[]
 3 for i in f:
 4     a.append(i.split())
 5 b=a[0]
 6 del a[0]
 7 a.sort(key=lambda x:(x[2],-int(x[3])))
 8 a.insert(0,b)
 9 f.close()
10 f=open('data4_processed.txt','w',encoding='utf-8')
11 for m in a:
12     for n in m:
13         f.write(n+'\t')
14     f.write('\n')
15 f=open('data4_processed.txt','r',encoding='utf-8')
16 c=f.read()
17 print(c)    

 

 

task5

 1 f=open('data5.txt','r',encoding='utf-8')
 2 data=f.read()
 3 lines=len(data.splitlines())
 4 words=len(data.split())
 5 spaces=data.count(' ')
 6 characters=len(data)
 7 print(f'行数:{lines}\n单词数:{words}\n空格数:{spaces}\n字符数:{characters}')
 8 a=open('data5_with_line.txt','w',encoding='utf-8')
 9 b=data.splitlines()
10 for i in range(len(b)):
11     a.writelines(f'{i+1} {b[i]}\n')
12 a.close()

 

 

 

posted on 2022-05-16 20:19  VolcanX  阅读(7)  评论(3编辑  收藏  举报