首页 > 编程语言 >实验5 文件应用编程

实验5 文件应用编程

时间:2023-06-06 20:55:45浏览次数:35  
标签:文件 items 编程 list stu 实验 print data id

实验任务6

task6

# 读取并处理原始数据with open('data6.csv','r',encoding = 'gbk') as f:
    old_data = f.read().split('\n')
del old_data[0]
#  四舍五入得到新数据
new_data = []
for i in range(len(old_data)):
    if eval(old_data[i]) + float(0.5) >= int(eval(old_data[i])) + 1:
        new_data.append(str(int(eval(old_data[i]))+1))
    else:
        new_data.append(str(int(eval(old_data[i]))))
# 形成二维列表
title = ['原始数据','四舍五入后数据']
data = []
for i in range(len(old_data)):
    data.append([old_data[i],new_data[i]])
# 写入
with open('data6.csv','w',encoding = 'gbk') as f:
    f.write(','.join(title) + '\n')
    for i in data:
        f.write(','.join(i) + '\n')
print('原始数据:')print(old_data)print('四舍五入后数据:')print(new_data)

运行结果如图:

实验任务7

 更新数据:

# 读取并处理信息
with open('data7.csv','r',encoding = 'gbk') as f:
    info = f.read().split('\n')
del info[0]

# 首先按专业排序
# 以专业为值创建字典
major_dict = {}
for i in info:
    person_list = i.split(',')
    major_dict[i] = person_list[2]

# 排序
items = [[k,v] for k,v in major_dict.items()]
items.sort(key=lambda x:x[1])

# 将同一专业的学生放在一起,并按照分数排序
# 计算专业数量并建立专业列表
majors_count = 1
majors_list = []
for i in range(len(items)-1):
    if items[i+1][1] == items[i][1] and items[i][1] not in majors_list:
        majors_list.append(items[i][1])
        pass
    elif items[i+1][1] == items[i][1] and items[i][1] in majors_list:
        pass
    else:
        majors_list.append(items[i+1][1])
        majors_count += 1

# 将相同专业学生放在一起:
for i in range(majors_count):
    x = locals()[f'major{i+1}'] = []  # 循环创建变量
    for j in range(len(items)):
        if items[j][1] == majors_list[i]:
            x.append(items[j][0])
        else:
            pass

# 每个专业内按照分数排序
# 以分数为值创建字典并排序
score_dict1 = {}
for i in major1:
    person_list = i.split(',')
    score_dict1[i] = person_list[3]
items1 = [[k,v] for k,v in score_dict1.items()]
items1.sort(key=lambda x:x[1],reverse = True)

score_dict2 = {}
for i in major2:
    person_list = i.split(',')
    score_dict2[i] = person_list[3]
items2 = [[k,v] for k,v in score_dict2.items()]
items2.sort(key=lambda x:x[1],reverse = True)

together = items1 + items2
final_data = [i[0] for i in together]

# 更新数据文件
final_list = []
for i in final_data:
    person_list = i.split(',')
    final_list.append(person_list)
print(final_list)
title = ['学号','姓名','专业','分数']

with open('data7.csv', 'w', encoding = 'gbk') as f:
    f.write(','.join(title) + '\n')
    for item in final_list:
        f.write(','.join(item) + '\n')

运行结果如图:

实验任务8

# 统计lines_count = 0
words_count = 0
chrs_count = 0
space_count = 0
with open('hamlet.txt','r',encoding = 'utf-8') as f:
    for line in f:
        words = line.split()
        lines_count += 1
        words_count += len(words)
        chrs_count += len(line)
        for i in list(line):
            if i == ' ':
                space_count += 1
            else:
                pass

print('行数:',lines_count)
print('单词数:',words_count)
print('字符数:',chrs_count)
print('空格数:',space_count)

运行结果如图:

# 给每一行加上序号
with open('hamlet.txt','r',encoding = 'utf-8') as f:
    text = f.readlines()

for i in range(len(text)):
    if text[i]:
        text[i] = str(i+1) + ' ' + text[i]

with open('hamlet.txt','w',encoding = 'utf-8') as f:
        f.writelines(text)

运行结果如图:

 

实验任务9

# 判断是否合法
def is_valid(p_id):
    if len(p_id) != 18:
        return False
    else:
        a = p_id[-1]
        b = p_id[:-1]
        if b.isdigit() == True and a == 'X' or p_id.isdigit() == True:
            return True
        else:
            return False

# 读取并筛选出合法的数据
with open('data9_id.txt','r',encoding = 'utf-8') as f:
    info = f.read().split('\n')
    del info[0]
    id_list = []
    for i in info:
        x = i.split(',')
        if x[0] not in id_list and is_valid(x[1]) == True:
            id_list.append([x[0],x[1]])

# 每个人的出生年月日,
import datetime
t = datetime.datetime.now()
year_now = int(t.strftime('%Y%m%d')[0:4])
month_now = int(t.strftime('%Y%m%d')[4:6])
day_now = int(t.strftime('%Y%m%d')[6:8])

year_dict = {}
for i in range(len(id_list)):
    p_id = id_list[i][1]
    year = int(p_id[6:10])
    month = int(p_id[10:12])
    day = int(p_id[12:14])

    p_info = id_list[i][0] + ',' + str(year) + '-' + str(month) + '-' + str(day) + ','
    if month <= month_now and day < day_now: # 判断今年是否已经过生日
        year_dict[p_info] = year_now - year - 1
    else:
        year_dict[p_info] = year_now - year

# 排序
print('姓名,出生日期,年龄')
items = [[k,v] for k,v in year_dict.items()]
items.sort(key=lambda x:x[1],reverse = True)
for i in items:
    print(f'{i[0]}{i[1]}')

运行结果如图:

实验任务十

task10_1

print(f"{'抽点开始':*^40}")
import random as r
with open('data10_stu.txt','r',encoding = 'utf-8') as f:
        stu = f.readlines()
# 定义抽取函数
def the_lucky_dogs(n):
    stu_list = []
    while True:
        if n != 0:
            i = r.randint(0,len(stu)-1)
            if stu[i] not in stu_list:
                stu_list.append(stu[i])
                print(stu[i])
                n -= 1
            else:
                pass
        else:
            print(f"{'抽点结束':*^40}")
            break

# 抽取
n = int(input('输入随机抽点人数:'))
the_lucky_dogs(n)

运行结果如图:

task10_2

print(f"{'抽点开始':*^40}")
import random as r
with open('data10_stu.txt','r',encoding = 'utf-8') as f:
        stu = f.readlines()

# 定义抽取函数
def the_lucky_dogs(n):
    stu_list = []
    while True:
        if n != 0:
            i = r.randint(0,len(stu)-1)
            if stu[i] not in stu_list:
                stu_list.append(stu[i])
                print(stu[i])
                n -= 1
            else:
                pass
        else:
            break

    for i in stu_list: # 排除之前已经被抽到的学生
        stu.remove(i)
    
# 抽取
while True:
    n = int(input('输入随机抽点人数:'))
    if n != 0:
        the_lucky_dogs(n)
    else:
        print(f"{'抽点结束':*^40}")
        break

运行结果如图:

 

 

标签:文件,items,编程,list,stu,实验,print,data,id
From: https://www.cnblogs.com/fengguowanyueyi/p/17461696.html

相关文章

  • 实验5
    实验任务6task6.py1withopen('data6.csv','r',encoding='gbk')asf:2data1=f.read().split('\n')3deldata1[0]4print('原始数据:')5print(data1)67foriinrange(len(data1)):8data1[i]......
  • 第五节 5with管理文件操作上下文
    在Python中,进行文件操作时,需要打开文件、读写文件、关闭文件等过程。如果代码有错误或者忘记关闭文件就会导致程序出错或文件资源泄露问题。为了更方便、更安全地进行文件操作,Python提供了with语句来管理文件的操作上下文。使用with语句可以确保在任何情况下,文件都会被正确地关闭......
  • 使用ffmpeg合并两个音频文件
    #寻找指定路径下所有的wav文件find$filePath-iname"*.wav">wav.flist#依次取出每个wav文件,与test.wav进行合并forlinein`catwav.flist`doecho$lineffmpeg-ipath/to/test.wav-i$line-filter_complex"[0:a]volume=1,atrim=1:4[a1];[1:a]volume=0.5[a......
  • 特殊文件:XML的解析
            ......
  • 特殊文件:XML的创建
       ......
  • java8函数式编程
    1.什么是函数式编程每个人对函数式编程的理解不尽相同。但其核心是:在思考问题时,使用不可变值和函数,函数对一个值进行处理,映射成另一个值。2.Lambda表达式Stream<String>stream=Stream.of("张三","李四");2.1collect(toList())List<String>names=stream.collect(Colle......
  • 实验5 文件应用编程
    实验任务6task6实验源码1withopen('data6.csv','r',encoding='gbk')asf:2data1=f.read().split('\n')3deldata1[0]4print('原始数据:')5print(data1)67foriinrange(len(data1)):8data1[i......
  • 权重文件
    实验中,自己保存的权重文件链接:https://pan.baidu.com/s/1Zt4yfI29SKS1i0JpAeN1Vg?pwd=a2y1提取码:a2y1复制这段内容后打开百度网盘手机App,操作更方便哦......
  • 明明加载好了css,js文件,页面的样式还是不对的解决办法
    页面内容的格式乱七八糟的…用F12开发人员工具检查了一下,没有发现任何问题最后,求助了bobby老师答曰:你缺乏前端知识,浏览器中有缓存,ctrl+f5强制刷新一下就好了恩,好了…......
  • 特殊文件:XML概述
          ......