#6
实验内容:
1 #6 2 with open('data6.csv','r',encoding='gbk') as f: 3 f1=f.readlines() 4 f1=list(f1) 5 l1=[] 6 l2=[] 7 title=['原始数据','四舍五入后数据'] 8 info1=f1[1:] 9 f2=[[str(eval(i)),str(round(eval(i)))] for i in info1] 10 for i in f2: 11 l1.append((i[0])) 12 l2.append(eval(i[1])) 13 with open('data6_processed.csv', 'w', encoding = 'gbk') as f: 14 f.write(','.join(title) + '\n') 15 for j in f2: 16 f.write(','.join(j)+'\n') 17 print(f'{title[0]}:') 18 print(l1) 19 print(f'{title[1]}:') 20 print(l2)View Code
实验结果:
#7
实验内容:
1 #7 2 with open ('data7.csv','r',encoding='gbk') as f: 3 data=f.readlines() 4 l=[] 5 l1=[] 6 for i in data: 7 l.append(list((i).split(','))) 8 l[-1][-1]+='\n' 9 l=sorted(l,key=lambda x:x[3],reverse=True) 10 with open ('data7_processed.csv', 'w', encoding = 'gbk') as f: 11 for i in l: 12 f.write(','.join(i)) 13 print(' '.join(['学号','姓名','专业','分数'])) 14 for i in l[1:]: 15 i[-1]=str(eval(i[-1])) 16 print(' '.join(i))View Code
实验结果:
#8
实验内容:
1 #8 2 with open ('hamlet.txt','r') as f: 3 h=f.read() 4 lines=h.split('\n') 5 hs=len(lines) 6 words=h.split() 7 dcs=len(words) 8 zfs=len(h) 9 kgs=h.count(' ') 10 print('hamlet.txt粗略统计:') 11 print(f'行数:{hs}') 12 print(f'单词数:{dcs}') 13 print(f'字符数:{zfs}') 14 print(f'空格数:{kgs}') 15 c=1 16 with open('hamlet_with_line_number.txt','w') as f: 17 for i in lines: 18 f.write(f'{c} {i}+\n') 19 c+=1View Code
实验结果:
#9
实验内容:
1 #9 2 def is_valid(x): 3 x=list(x) 4 if len(x) !=18: 5 return False 6 for i in x[:-2]: 7 if i.isdigit(): 8 pass 9 else: 10 return False 11 break 12 if str(x[-1]) in ['0','1','2','3','4','5','6','7','8','9','X']: 13 return True 14 else: 15 return False 16 17 import datetime 18 t=datetime.datetime.now() 19 t=t.strftime('%Y%m%d') 20 21 with open('data9_id.txt','r') as f: 22 data=f.read() 23 data=data.split('\n') 24 l=[] 25 l2=[] 26 for i in data: 27 i=i.split(',') 28 l.append(list(i)) 29 for i in l[1:]: 30 if is_valid(i[1]) is True: 31 p=f'{i[1][6:10]}-{i[1][10:12]}-{i[1][12:14]}' 32 age=int(t[0:4])-int(i[1][6:10]) 33 if int(t[4:8])-int(i[1][10:14])>=0: 34 age+=1 35 else: 36 age-=1 37 l2.append([i[0],p,age]) 38 l2=sorted(l2,key=lambda x:x[2],reverse=True) 39 print('姓名, 出生日期, 年龄') 40 for i in l2: 41 print(f'{i[0]}, {i[1]}, {i[2]}')View Code
实验结果:
#10
实验内容:
1 import datetime 2 import random 3 t=datetime.datetime.now() 4 t=t.strftime('%Y%m%d') 5 6 with open ('data10_stu.txt','r') as f: 7 stu=f.read() 8 stu=stu.split('\n') 9 10 l=[] 11 for i in stu: 12 l.append(i) 13 c=[i for i in range(0,len(l))] 14 n=int(input('输入随机抽点人数:')) 15 for i in range(n): 16 j=random.sample(c,5) 17 18 with open (f'{t}.txt','w') as f: 19 for i in j: 20 print(l[i]) 21 f.write(l[i]+'\n')View Code
实验结果:
标签:10,12,14,l2,print,实验,open From: https://www.cnblogs.com/047lishiqi/p/17445683.html