task6
with open('data6.csv','r',encoding='gbk') as f: data=f.readlines() data.remove('原始数据\n') data0=[] for i in data: if i[-1]=='\n': i=i[:-1] data0.append(float(i)) print('原始数据:') print(data0) data1=[int(i+0.5) for i in data0] print('四舍五入后数据:') print(data1) with open('data6_processed.csv','w',encoding='gbk') as f: f.write('原始数据,四舍五入后数据\n') for i in range(len(data1)): f.write(str(data0[i])+','+str(data1[i])+'\n')
task7
with open('data7.csv','r',encoding='gbk') as f: data1 = f.read().split('\n') del data1[0] lsta = [] lstm = [] for i in data1: lst1 = i.split(',') if lst1[2] == 'Acting': lsta.append(lst1) else:lstm.append(lst1) lstm.sort(reverse = False) lsta.sort(reverse = False) info = lsta + lstm title = ['学号','姓名','专业','分数'] with open('data7_processed.csv','w',encoding='utf-8') as f: f.write(','.join(title)+'\n') for items in info: f.write(','.join(items)+'\n') print('{:<10}'.format(title[0]),'{:<10}'.format(title[1]),'{:<10}'.format(title[2]),'{:<15}'.format(title[3])) for i in info: print('{:<10}'.format(i[0]),'{:<10}'.format(i[1]),'{:<10}'.format(i[2]),'{:<15}'.format(i[3]))
task8
with open('hamlet.txt','r',encoding = 'gbk') as f: lst = f.readlines() a = len(lst) print('hamlet.txt粗略统计:') print('行数:',a) lst0 = [] for k in lst: lst0 += k.split(' ') e = len(lst0) print('单词数:',e) lst1 = [] for i in lst: lst1 += list(i) b = len(lst1) print('字符数:',b) c = lst1.count(' ') print('空格数:',c) with open('hamlet_with_line_number.txt','w',encoding = 'gbk') as f: for t in range(len(lst)): text = lst[t] f.write(f'{t+1} {text}')
task9
def is_valid(sfz): if len(sfz) != 18: return False elif (sfz[:-1].isnumeric() and sfz[-1] == 'X') or sfz.isnumeric(): return True else:return False with open('data9_id.txt','r',encoding='utf-8') as f: data = f.read().split('\n') del data[0] data2 = [] data3 =[] print('姓名,出生日期,年龄') for i in data: lst = i.split(',') data2.append(lst) lst2 = [] for i in data2: if is_valid(i[1]) == True: name = i[0] btd = i[1][6:14] age = str(2023 - int(i[1][6:10])) lst2.append([name,btd,age]) lst2.sort(key=lambda x:x[2],reverse=True) for i in lst2: print(i[0],end=',') print(f'{i[1][:4]}-{i[1][4:6]}-{i[1][6:8]}',end=',') print(i[2])
task10
with open('data10_stu.txt','r',encoding='utf-8') as f: data = f.readlines() print('{:*^40}'.format('抽点开始')) n = int(input('输入随机抽点人数:')) import random x = [] x2 = '' counts = 0 while counts < n: new = random.randint(0, len(data) - 1) if new in x: new = random.randint(0, len(data) - 1) else: counts +=1 x.append(new) for i in range(n): print(data[x[i]]) x2 += data[x[i]] sum1 += n with open('20230602.txt','w',encoding='utf-8') as f: f.writelines(x2)
标签:文件,lst1,encoding,open,编程,lst,实验,print,data From: https://www.cnblogs.com/myt1/p/17457378.html