首页 > 其他分享 >实验5

实验5

时间:2023-06-06 23:23:34浏览次数:38  
标签:datetime num 实验 print line data id

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

相关文章

  • 实验五 文件应用编程
    实验五 文件应用编程 实验任务六程序源代码:1withopen('data6.csv','r',encoding='gbk')asf:2old_data=f.read().split('\n')3delold_data[0]4processed_data=[]5foriinrange(len(old_data)):6ifeval(old......
  • 实验5 文件应用编程
    实验任务1:统计文件行数(不统计空白行)task1_1.py'''统计文件data1.txt行数(不包括空白行)data1.txt中的空白行包括由空格、Tab键(\t)、换行(\n)构成的空白行'''withopen('data1.txt','r',encoding='utf-8')asf:data=f.readlines()n=0fo......
  • 野火STM32第35章 SDIO读写测试 实验过程犯的错误:卡在while(SD_GetStatus() != SD_TRAN
    看完书,我自己重新写了一遍代码。写代码过程中,对DMA以下标绿的部分很不以为意。1voidSD_DMA_TxConfig(uint32_t*DMA_Tx_Buf,uint32_tBufferSize)2{3DMA_InitTypeDefDMA_InitStruct;45/*ClockEnable-----InGPIOConfig*/67/*Flag......
  • 实验7 面向对象编程与内置模块
    task1.pycode:classAccount:def__init__(self,name,account_number,initial_amount=10):self._name=nameself._card_no=account_numberself._balance=initial_amountdefdeposit(self,amount):self._balance+=a......
  • 实验5 文件应用编程
    task6源代码:withopen('data6.csv','r',encoding='gbk')asf:data1=f.read().split('\n')deldata1[0]foriinrange(len(data1)):data1[i]=eval(data1[i])data1[i]=float(data1[i])print('原始数据:&#......
  • 实验5 文件应用编程
    实验任务61withopen('data6.csv','r',encoding='gbk')asf:2data1=f.read().split('\n')3deldata1[0]4foriinrange(len(data1)):5data1[i]=eval(data1[i])6data1[i]=float(data1[i])7pri......
  • 实验6 turtle绘图与python库应用编程体验
    实验任务1task1_1fromturtleimport*defmoveto(x,y):'''画笔移动到坐标(x,y)处'''penup()goto(x,y)pendown()defdraw(n,size=100):'''绘制边长为size的正n边形'''for......
  • 实验5
    1withopen('data6.csv','r',encoding='gbk')asf:2data1=f.read().split('\n')3deldata1[0]4print('原始数据:')5print(data1)67foriinrange(len(data1)):8data1[i]=float(data1[i]......
  • 实验5 文件应用编程
    实验任务6task6#读取并处理原始数据withopen('data6.csv','r',encoding='gbk')asf:old_data=f.read().split('\n')delold_data[0]#四舍五入得到新数据new_data=[]foriinrange(len(old_data)):ifeval(old_data[i])+flo......
  • 实验5
    实验任务6task6.py1withopen('data6.csv','r',encoding='gbk')asf:2data1=f.read().split('\n')3deldata1[0]4print('原始数据:')5print(data1)67foriinrange(len(data1)):8data1[i]......