sunchenxi

导航

实验5 文件应用编程

 1 #task3.py
 2 with open('data3.txt','r',encoding='utf-8') as f :
 3     with open('data3_processed.txt', 'w', encoding='utf-8') as f1:
 4         data=f.read().strip().split('\n')
 5         data.pop(0)
 6         data1=[eval(i) for i in data]
 7         data2=[]
 8         for i in data1:
 9             if i - int(i) >= 0.5:
10                 data2.append(int(i) + 1)
11             else:
12                 data2.append(int(i))
13         data3=[int(i)for i in data2]
14         f1.write(f'原始数据\t四舍五入后的数据\n')
15         for j in range(len(data)):
16             f1.write(f'{data1[j]}\t\t{data2[j]}\n')
17     print(f'原始数据:\n{data1}\n四舍五入后的数据:\n{data2}')

 1 #task4.py
 2 with open('data4.txt','r',encoding='utf-8')as f:
 3     with open('data4_processed.txt','w',encoding='utf-8')as f1:
 4         data=f.readlines()
 5         data1=[i.strip('\n').split('\t') for i in data]
 6         x=data1.pop(0)
 7         data2=[sorted(data1,key=lambda x: (x[2], -int(x[3])))]
 8         print('\t\t'.join(x))
 9         f1.write('\t\t'.join(x)+'\n')
10         for i in data2:
11             for j in i:
12                 print('\t'.join(j))
13                 f1.write('\t'.join(j)+'\n')

 1 #task5.py
 2 with open('data5.txt','r',encoding='utf-8')as f:
 3     with open('data5_with_line.txt', 'w', encoding='utf-8') as f1:
 4         a=f.read().strip('\n')
 5         b = len(a.splitlines())
 6         print('行数:', b)
 7         e = len(a.split())
 8         print('单词数:', e)
 9         c = 0
10         for c, number in enumerate(a):
11             c += 1
12         print('字符数:', c)
13         d = 0
14         for i in a:
15             if i == ' ':
16                 d += 1
17         print('空格数:', d)
18         a=a.split('\n')
19         n='\n'.join(a)
20 
21         for i in range(len(a)):
22             f1.write(f'{i+1}.{a[i]}\n')

 

posted on 2022-05-14 16:01  靠谱一星  阅读(16)  评论(1编辑  收藏  举报