首页 > 其他分享 >实验五

实验五

时间:2023-06-05 17:34:32浏览次数:43  
标签:num 实验 processed print line data id

with open('data6.csv', 'r',encoding = 'gbk') as f:
      data = f.readlines()
processed_data = []
for i in range(1, len(data)):
    row = data[i].strip()
    processed_item = round(float(row))
    processed_data.append(processed_item)
with open('data6_processed.csv', 'w',encoding = 'gbk') as f:
    f.write('原始数据,四舍五入后的数据\n')
    for i in range(len(processed_data)):
        f.write(data[i+1].strip() + ',' + str(processed_data[i])+'\n')
print('原始数据:')
print( [float(d.strip()) for d in data[1:]])
print('四舍五入后的数据:')
print(processed_data)

  

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))

  

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]))

  

import datetime

def is_valid(id_num):
    """
    判断身份证号码是否有效
    """
    
    if len(id_num) != 18:
        return False
    
    if not id_num[:17].isdigit():
        return False
    
    if id_num[17] not in '0123456789X':
        return False
    return True

with open('data9_id.txt', 'r',encoding='utf-8') 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))

  

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)

  

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))

  

 

标签:num,实验,processed,print,line,data,id
From: https://www.cnblogs.com/yhyy/p/17458506.html

相关文章

  • 实验5
    6.实验任务6程序源代码:withopen('data6.csv','r',encoding='gbk')asf:data=f.readlines()data_title=['原始数据','四舍五入后数据']data.remove('原始数据\n')data_zahl=[]foriindata:ifi[-1]==�......
  • 实验6
      task5-1fromturtleimport*importmathdefmove(x,y):penup()goto(x,y)pendown()defmain():x=100*math.sqrt(2)pensize(2)move(-100,-100)begin_fill()forward(200)left(90)forward(200)left(90)......
  • 实验6 turtle绘图与python库应用编程体验
    任务1fromturtleimport*defmove(x,y):penup()goto(x,y)pendown()defdraw(n,size=100):foriinrange(n):fd(size)left(360/n)defmain():pensize(2)pencolor('red')move(-200,0)draw(3)mov......
  • 实验5
    withopen('data6.csv','r',encoding='gbk')asf:data=f.readlines()data1=[str(eval(data[i]))foriinrange(1,len(data))]data2=[str(int(eval(data[i])+0.5))foriinrange(1,len(data))]info=[[data1[i],data2[i]]forii......
  • 实验5 文件应用编程
    实验任务6:实验源码:withopen('data6.csv','r',encoding='gbk')asf:data=f.readlines()data1=[str(eval(data[i]))foriinrange(1,len(data))]data2=[str(int(eval(data[i])+0.5))foriinrange(1,len(data))]info=[[data1[i],dat......
  • Python实验课5
    实验任务六实验源码:1withopen('data6.csv','r',encoding='gbk')asf:2data=f.readlines()3data1=[str(eval(data[i]))foriinrange(1,len(data))]4data2=[str(int(eval(data[i])+0.5))foriinrange(1,len(data))]5info=......
  • 实验5
    实验任务6实验源码:withopen('C:/Users/Lenovo/Desktop/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......
  • 实验6 turtle绘图与python库应用编程体验
    task1_1fromturtleimport*defmove(x,y):penup()goto(x,y)pendown()defdraw(n,size=100):foriinrange(n):fd(size)left(360/n)defmain():pensize(2)pencolor('red')move(-200,0)draw(3)......
  • 实验报告
    https://www.cnblogs.com/yycyhyhf/p/17264251.htmlhttps://www.cnblogs.com/yycyhyhf/p/17285673.htmlhttps://www.cnblogs.com/yycyhyhf/p/17378885.htmlhttps://www.cnblogs.com/yycyhyhf/p/17239138.htmlhttps://www.cnblogs.com/yycyhyhf/p/17327753.html......
  • 实验二——验收三
    验收三1.你们小组项目中为了保护数据资产用了什么密码算法?2.如果用到了对称算法,提交相关生成密钥和对数据加密的代码截图3.如果用到了非对称算法,提交相关生成密钥对和对数据加密,签名验签的代码截图4.如果用到了其他算法,提交相关的代码截图1.算法使用①口令哈希值:sm3......