task6
源码:
import csv with open('data6.csv', 'r', encoding='gbk') as f: data_o = f.readlines() for i in range(len(data_o)): data_o[i] = data_o[i].strip('\n') #原始数据 del data_o[0] #处理后数据 data_1 = [] for d_o in data_o: d_1 = round(float(d_o)) data_1.append(d_1) title = ['原始数据','四舍五入后数据'] with open('data6_processed.csv','w',encoding='gbk',newline='') as f2: f2_writer = csv.writer(f2) f2_writer.writerow(title) for i in range(len(data_1)): f2.write(data_o[i] + ',' + str(data_1[i])+'\n') print("原始数据:",end='') print([float(d) for d in data_o]) print("四舍五入后数据:",end='') print(data_1)
截图:
task7:
源码
with open('data7.csv', 'r',encoding='gbk') as f: data = f.readlines() datas = {} for i in range(1, len(data)): row = data[i].strip().split(',') student_id, name, major, score = row[0], row[1], row[2], int(row[3]) if major not in datas: datas[major] = [] datas[major].append({'学号': student_id, '姓名': name, '分数': score}) with open('data7_processed.csv', 'w',encoding='gbk') as f: f.write('学号,姓名,专业,分数\n') for major in sorted(datas.keys()): major_data = sorted(datas[major], key=lambda k: k['分数'], reverse=True) for item in major_data: f.write(item['学号'] + ',' + item['姓名'] + ',' + major + ',' + str(item['分数']) + '\n') print('{:<8}\t{:<8}\t{:<8}\t{}'.format('学号', '姓名', '分数', '专业')) for major in sorted(datas.keys()): major_data = sorted(datas[major], key=lambda k: k['分数'], reverse=True) for item in major_data: print('{:<8}\t{:<8}\t{:<8}\t{}'.format(item['学号'], item['姓名'], str(item['分数']), major))
截图
task8:
源码:
with open('hamlet.txt', 'r') as f: text = f.read() lines = text.split('\n') words = text.split() num_chars = len(text) num_spaces = text.count(' ') print('行数:', len(lines)) print('单词数:', len(words)) print('字符数:', len(text)) print('空格数:', num_spaces) with open('hamlet_with_line_number.txt', 'w') as f: for i in range(len(lines)): f.write('{:>4} {}\n'.format(i+1, lines[i]))
截图:
task9:
源码:
import datetime def is_valid(id_num): """ 判断身份证号码是否有效 """ # 长度必须为18位 if len(id_num) != 18: return False # 前17位必须都是数字 if not id_num[:17].isdigit(): return False # 最后一位只能是数字或大写字母X if id_num[17] not in '0123456789X': return False return True with open('data9_id.txt', 'r') as f: lines = f.readlines() id_list = [] for line in lines: line = line.strip() if line.startswith('姓名'): continue name, id_num = line.split(',') if is_valid(id_num): birth_str = id_num[6:14] birth_date = datetime.datetime.strptime(birth_str, '%Y%m%d') age = (datetime.datetime.now() - birth_date).days // 365 id_list.append((name, birth_date, age)) # 按照年龄降序输出姓名、出生日期、当前年龄 id_list.sort(key=lambda x: x[2], reverse=True) for name, birth_date, age in id_list: print('{}\t{}\t{}'.format(name, birth_date.strftime('%Y-%m-%d'), age))
截图:
task10_1:
源码:
import random import datetime with open('data10_stu.txt', 'r', encoding='utf-8') as f: data = f.readlines() n = int(input('随机抽点人数:')) ran_data = random.sample(data, n) for line in ran_data: line = line.strip().split('\t') print('{:<12}{:<12}{}'.format(line[0], line[1], line[2])) file_name = datetime.datetime.now().strftime('%Y%m%d') + '.txt' with open(file_name, 'w', encoding='utf-8') as f: f.write('学号\t姓名\t班级\n') f.writelines(ran_data)
截图:
task10_2
源码
import random import datetime with open('data10_stu.txt', 'r', encoding='utf-8') as f: data = f.readlines() print(f"{'抽点开始':*^40}") while True: n = int(input('输入随点抽取人数:')) if n == 0: break ran_data = random.sample(data, n) for line in ran_data: line = line.strip().split('\t') print('{:<12}{:<12}{}'.format(line[0], line[1], line[2])) print(f"{'抽点结束':*^40}") file_name = datetime.datetime.now().strftime('%Y%m%d') + '.txt' with open(file_name, 'a', encoding='utf-8') as f: f.writelines(set(ran_data))
截图:
实验总结:
1.在计算年龄时,使用了datetime模块中的datetime类。导入模块可以使代码简洁很多。该类表示一个日期和时间的组合,可以进行各种日期和时间的计算和比较。datetime.datetime.now()方法可以获取当前日期和时间,然后将其减去出生日期,得到一个时间差,再将时间差的天数除以365,得到当前年龄。
2.task10.2中,while循环支持用户多次输入进行抽点,直到抽点人数输入0时终止。同时,在保存随机抽取结果到文件中时,可以使用set去除重复名单。
标签:datetime,num,实验,print,line,data,id From: https://www.cnblogs.com/minkongchan/p/17462032.html