实验6 文件应用编程-2

task3.py

 1 def is_valid(a):
 2     l=0
 3     f=0
 4     for i in a:
 5         l+=1
 6         if '0'<=i<='9' or i=='X':
 7             pass
 8         else:
 9             f+=1
10             break
11     if l!=18 or f!=0:
12         return False
13     if l==18 and f==0:
14         return True
15 with open("data3_id.txt","r",encoding="utf-8") as f:
16     data=f.readlines()
17 b=[]
18 for i in range(1,len(data)):
19     f=data[i][3::].strip()
20     if is_valid(f)==True:
21         b.append(data[i])
22 f3=[]
23 f4=[]
24 for i in b:
25     name=i[:2:]
26     year=i[9:13:]
27     month=i[13:15:]
28     day=i[15:17:]
29     flag=[year,month,day]
30     flag1="-".join(flag)
31     f3.append(flag1)
32     flag=[name,flag1]
33     flag2=",".join(flag)
34     f4.append(flag2)
35 f3=sorted(f3,reverse=False)
36 answer=[]
37 for i in f3:
38     for j in f4:
39         if i in j:
40             answer.append(j)
41 for i in answer:
42     print(i)

运行结果截图

 

task5_1.py

 1 with open("data5.txt","r",encoding="utf-8") as f:
 2     d=f.readlines()
 3 import random
 4 n=int(input("输入随机抽点人数:"))
 5 f1=set()
 6 l=len(f1)
 7 while l<n:
 8     f=random.randint(0,len(d))
 9     f1.add(d[f])
10     l=len(f1)
11 for i in f1:
12     print(i,end="")
13 with open("20220518.txt","w",encoding="utf-8") as f:
14     for i in f1:
15         f.write(i)

运行结果截图

 

task5_2.py

 1 with open("data5.txt","r",encoding="utf-8") as f:
 2     d=f.readlines()
 3 import random
 4 with open("20220518_1.txt","a",encoding="utf-8") as f11:
 5     flag = 1
 6     while (flag == 1):
 7         n = int(input("输入随机抽点人数:"))
 8         if n == 0:
 9             flag = 0
10         else:
11             f1 = set()
12             l = len(f1)
13             while l < n:
14                 f = random.randint(0, len(d))
15                 f1.add(d[f])
16                 l = len(f1)
17             for i in f1:
18                 print(i, end="")
19                 f11.write(i)

运行结果截图

 

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