实验6 文件应用编程
作者:互联网
task.3.py
def is_valid(s): if len(s)!=18: return False elif s.isdigit()==bool(1) or 'X' in s : return bool(1) else: return False with open('D:\\data3_id.txt','r',encoding='utf-8') as f: d1=f.readlines() l1=[] l2=[] l3=[] for line in d1: line=line.strip('\n') line=list(line.split(',')) s=''.join(line[1]) if is_valid(s): l3.append(line) for i in range(len(l3)): l1.append(l3[i][0]) a=l3[i][1][6:10] b=l3[i][1][10:12] c=l3[i][1][12:14] l2.append(a+'-'+b+'-'+c) d1=dict(zip(l1,l2)) d2=sorted(d1.items(),key=lambda x:x[1]) for k in d2: print(f'{k[0]}:{k[1]}')
task.5-1.py
import random import datetime t=datetime.datetime.now() filename=t.strftime('%Y%m%d')+'.txt' with open('D:\\data5.txt','r',encoding='utf-8') as f: d1=f.readlines() l1=[] for line in d1: line=line.strip('\n') line=line.split('\t') l1.append(line) n=int(input('输入随机抽点的人数n:')) b=random.sample(l1,n) d=''.join(str(b)) with open(filename,'w',encoding='utf-8') as f: for i in b: c=' '.join(i) f.writelines(c+'\n') print(c)
task.5-2.py
import random import datetime t=datetime.datetime.now() filename=t.strftime('%Y%m%d')+'.txt' with open('D:\\data5.txt','r',encoding='utf-8') as f: d1=f.readlines() l1=[] for line in d1: line=line.strip('\n') line=line.split('\t') l1.append(line) file=open (filename,'w',encoding='utf-8') a=2 while a==2: n=int(input('输入随机抽点的人数n:')) if n!=0: b=random.sample(l1,n) for j in b: l1.remove(j) c=' '.join(j) print(c) file.writelines(c+'\n') else: print('{:=^40}'.format('抽点结束')) break file.close()
实验总结:1.在排序时可以将列表转换为字典再利用lambda(x:代表要进行排序参数的位置)函数对值进行排序,不改变相应的键值对应关系
2.list.append(a+b+c)可以用加号连接进行多个字符串连成一个字符串写进列表中
3.''.join(list)可以实现将列表转换为字符串
标签:文件,编程,datetime,实验,l3,l1,line,append,d1 来源: https://www.cnblogs.com/123gan/p/16295530.html