实验五 文件应用编程

task3.py

 1 with open("data3.txt","r",encoding="utf-8") as f:
 2     d=f.readlines()
 3     flag=d
 4 with open("data3_processed.txt","a",encoding="utf-8") as f1:
 5     for i in flag:
 6         f1.writelines(i)
 7 for i in range(len(d)):
 8     d[i]=d[i].strip()
 9 a=[]
10 for k in d[1::]:
11     k=float(k)
12     a.append(k)
13 print(f"{d[0]}:\n{a}")
14 a1=[]
15 for j in a:
16     j=round(float(j))
17     a1.append(j)
18 print(f"四舍五入后数据:\n{a1}")
19 a1.insert(0,"四舍五入后数据")
20 a1[0]="\n"+a1[0]
21 for i in range(len(a1)):
22     a1[i]=str(a1[i])
23     a1[i]=a1[i]+"\n"
24 with open("data3_processed.txt","a",encoding="utf-8") as f1:
25     for i in a1:
26         f1.writelines(i)

运行结果截图

 

 

task4.py

 1 with open("data4.txt","r",encoding="utf-8") as f:
 2     d=f.readlines()
 3 a=[]
 4 for i in d:
 5     a.append(i.strip().split(sep="\t"))
 6 x=[]
 7 z=[]
 8 for i in a:
 9     x.append(i[0])
10     z.append(i[2])
11 x=x[1::]
12 z=z[1::]
13 flag1=list(zip(z,x))
14 flag1=sorted(flag1)
15 flag2=[]
16 flag2.append(a[0])
17 for i in flag1:
18     for j in a:
19         if j[0]==i[1]:
20             flag2.append(j)
21 x1=[]
22 f1=[]
23 x2=[]
24 f2=[]
25 for i in flag2:
26     if i[2]=='Acting':
27         x1.append(i[0])
28         f1.append(i[3])
29     elif i[2]=='Music':
30         x2.append(i[0])
31         f2.append(i[3])
32 flag3=sorted(list(zip(f1,x1)),reverse=True)
33 flag4=sorted(list(zip(f2,x2)),reverse=True)
34 flag5=[]
35 flag5.append(flag2[0])
36 for i in flag3:
37     for j in flag2:
38         if j[0]==i[1]:
39             flag5.append(j)
40 for i in flag4:
41     for j in flag2:
42         if j[0]==i[1]:
43             flag5.append(j)
44 flag6=[]
45 for i in flag5:
46     i="\t".join(i)
47     flag6.append(i+"\n")
48 for i in flag6:
49     print(i)
50 with open("data4_processed.txt","w",encoding="utf-8") as f:
51     for i in flag6:
52         f.writelines(i)

运行结果截图

 

 

task5.py

 1 with open("data5.txt","r",encoding="utf-8") as f:
 2     d=f.readlines()
 3 l=1
 4 dan=0
 5 k=0
 6 z=0
 7 for i in d:
 8     if i!="\n":
 9         i1=i.split()
10         for i2 in i1:
11             dan+=1
12     for j in i:
13         z+=1
14         if j=='\n':
15             l+=1
16         if j==" ":
17             k+=1
18 print(f"行数:{l}")
19 print(f"单词数:{dan}")
20 print(f"空格数:{k}")
21 print(f"字符数:{z}")

运行结果截图

 

posted @ 2022-05-16 19:05  昏汐  阅读(10)  评论(2编辑  收藏  举报