实验5 文件应用编程

1,实验任务3

 1 with open('data3.txt','r',encoding='utf-8') as f:
 2    data=f.read()
 3 a=[]
 4 data=data.split('\n')
 5 for i in range(len(data)):
 6     if i!=0:
 7         a.append(float(data[i]))
 8 print(data[0],':')
 9 print(a)
10 b=[]
11 for i in a:
12     x=round(i)
13     b.append(x)
14 print('四舍五入后的数据:')
15 print(b)
16 with open('data3_processed.txt','w',encoding='utf-8') as f:
17     f.write('原始数据\t')
18     f.write('四舍五入后数据')
19     f.write('\n')
20     for i in range(len(a)):
21         f.write(str(a[i]))
22         f.write('\t')
23         f.write(str(b[i]))
24         f.write('\n')

运行结果:

2,实验任务4

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

运行结果:

3,实验任务5:

 1 with open('data5.txt','r') as f:
 2     a=''.join(f)
 3     x=len(a.splitlines())
 4     y=len(a.split())
 5     z=a.count(' ')
 6     b=len(a)
 7 print('行数:',x)
 8 print('单词数:',y)
 9 print('空格数:',z)
10 print('字符数:',b)
11 c=a.splitlines()
12 with open('data5_with_line.txt','w') as f:
13     for i in range(0,len(c)):
14         f.write(str(i+1))
15         f.write(' ')
16         f.write(str(c[i]))
17         f.write('\n')

运行结果:

 

posted @ 2022-05-16 20:49  炸呼  阅读(8)  评论(3编辑  收藏  举报