首页 > 其他分享 >实验5

实验5

时间:2023-06-06 16:13:09浏览次数:34  
标签:encoding open random 实验 print line data

task6

with open('data6.csv','r',encoding='gbk')as f:
    data=list(f.readlines())
data=[i.strip('\n') for i in data ]

import decimal
decimal.getcontext().rounding='ROUND_HALF_UP'
title=[data[0],'四舍五入后的数据']
data_new=[]
data_o=[]
for i in data:
    if not i.isalpha() is True:
        data_o.append(eval(i))
print('原始数据:')
print(data_o)
for i in data:
    if not i.isalpha() is True:
        data_new.append([i])

data_=[]
for i in data:
    if not i.isalpha() is True:
        index=data.index(i)-1
        i=eval(i)
        if i-int(i)>=0.5:
            i=int(i)+1
            data_new[index].append(str(i))
            data_.append(i)
        else:
            i=int(i)
            data_new[index].append(str(i))
            data_.append(i)
print('四舍五入后的数据:')
print(data_)
import csv
with open('data6_after.csv','w',encoding='gbk',newline='') as f :
    f_writer=csv.writer(f)
    f_writer.writerow(title)
    f_writer.writerows(data_new)
View Code

 task7

with open('data7.csv','r',encoding='gbk')as f:
    title=[f.readline()]
    data=f.readlines()
def getscore(ls):
    return ls[len(ls)-1]

data=[line.strip('\n').split(',')for line in data]

data.sort(key=lambda x:(x[2],-int(x[3])))


with open('data7_processed.csv', 'w', encoding = 'gbk') as f:
    f.write(','.join(title))
    for item in data:
        f.write(','.join(item) + '\n')
title=title[0].strip('\n').split(',')

print('{:<10}'.format(title[0]),'{:<10}'.format(title[1]),'{:<10}'.format(title[2]),'{:<15}'.format(title[3]))
for i in data:
    print('{:<10}'.format(i[0]), '{:<10}'.format(i[1]), '{:<10}'.format(i[2]), '{:<10}'.format(i[3]))
View Code

 

 

 task8

with open('hamlet.txt','r',encoding='utf-8')as f:
    data=f.readlines()
    print('行数:',len(data))

x=''
for line in data:
    x+=line
alpha=0
b=0
for i in x:
    if i.isalpha():
        alpha+=1
    else:
        b+=1

word=len(x.split())
print('字符数:',alpha+b)
print('单词数:',word)
print('空格数:',x.count(' '))
data = [line.strip('\n').split(',') for line in data]
with open('hamlet_with_line_number','w',encoding='utf-8') as f:
    for i,j in enumerate(data,start=1):
        j=j[0]
        f.write("{}{}{}".format(i,' ',j)+'\n')
View Code

 

task9

with open('data9_id.txt','r',encoding='utf-8')as f:
    data=f.readlines()

info=[line.strip('\n').split(',')for line in data]
del info[0]

def is_valid(id):
    y=id[:17]
    if (i in ['1','2','3','4','5','6','7','8','9','0','X'] for i in id) and len(id)==18 and y.isdigit() and (id[17]=='X' or id[17].isdigit()):
        return True
    else:
        return False
print('{:<10} {:<10} {:<10} '.format('姓名','出生日期','年龄'))
import datetime
today=datetime.date.today()
valid_ls=[]
for ls in info:
    if is_valid(ls[1]) is True:
        y, m, d = ls[1][6:10], ls[1][10:12], ls[1][12:14]
        birth = y + '-' + m + '-' + d
        ls.append(birth)
        del ls[1]
        birthday=datetime.date(year=int(y),month=int(m),day=int(d))
        age=str(round((today-birthday).days/365))
        ls.append(age)
        valid_ls.append(ls)
def takeThird(elem):
    return elem[2]
valid_ls.sort(key=takeThird,reverse = True)
for ls in valid_ls:
    for i in ls:
        print('{:8}'.format(i),end='    ')
    print()
View Code

 task10_1

import datetime
t = datetime.datetime.now()
filename = t.strftime('%Y%m%d') + '.txt'
n=eval(input('输入随机抽取人数:'))
with open('data10_stu.txt', 'r', encoding = 'utf-8') as f:
    data=f.readlines()


def random_selection(n):
    import random
    demo = random.sample(data, n)
    return demo
x=random_selection(n)
for i in x :
    print(i)


with open(filename,'w',encoding='utf-8')as f:
    f.writelines(x)
View Code

 

 task10_2

import datetime
t = datetime.datetime.now()
filename = t.strftime('%Y%m%d') + '.txt'
start='抽取开始'
print(start.center(50,'*'))
with open('data10_stu.txt', 'r', encoding='utf-8') as f:
    data = f.readlines()

def random_selection(n):
    import random
    demo = random.sample(data, n)
    return demo
selection=set()
numbers=[]

while True:
    n = eval(input('输入随机抽点人数:'))
    if n != 0:
        x=random_selection(n)
        for i in x:
            print(i)
            data.remove(i)
            with open(filename,'a',encoding='utf-8') as f :
                f.writelines(i)
    else:
        print('抽取结束'.center(50,'*'))
        break
View Code

 

 

 

标签:encoding,open,random,实验,print,line,data
From: https://www.cnblogs.com/yqyq/p/17460839.html

相关文章

  • 《大学物理实验上》期末笔记(一)不确定度的计算
    《大学物理实验上》期末笔记(一)不确定度的计算什么是不确定度?​ ★不确定度表示测量值可能变动(不能确定)的范围,也是与测量结果相关的一个参数,用于合理表示由于测量误差的存在而对被测量值的不能肯定的程度。​ 简单来说,我们测得一组值,分别为\(x_1,x_2,x_3...x_n\),我们可以通过......
  • 经纬恒润整车在环测试实验室发布新技术特性
        作为国内最早开展整车在环仿真测试技术预研的企业之一,经纬恒润自2016年起,正式启动了整车在环仿真相关技术的预研工作。整车在环实现了从半实物仿真到机械混合仿真的跨步,将功能测试与性能测试打包整合,从整车完整的功能和机械表现,评价了车辆整体能力。近年来,伴随着汽车行......
  • 2023年5月31日吴曦远202283820011实验五
    task1_1.pycode:withopen('data1.txt','r',encoding='utf-8')asf:data=f.readlines()n=0print(data)forlineindata:ifnotline.strip()=='':n+=1print(n)output:note:ifdelet"not"......
  • 实验5
    实验任务6withopen('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[i])p......
  • 实验6 turtle绘图和Python库应用编程体验
    实验任务1task1_1.py源代码1fromturtleimport*23defmove(x,y):4penup()5goto(x,y)6pendown()78defdraw(n,size=100):9foriinrange(n):10fd(size)11left(360/n)1213defmain():14pensize(2)1......
  • 实验5
     with open('data6.csv','r',encoding='gbk') as f:  data1 = f.read().split('\n')del data1[0]print('原始数据:')print(data1)for i in range(len(data1)):    data1[i] = float(data1[i])data2 = []for i in ra......
  • 实验6 turtle绘图与python库应用编程体验
    实验任务1task1_11fromturtleimport*23defmoveto(x,y):4'''5画笔移动到坐标(x,y)处6'''7penup()8goto(x,y)9pendown()1011defdraw(n,size=100):12'''13绘制边长为s......
  • 实验五 文件应用编程
    实验任务61#读取并处理原始数据withopen('data6.csv','r',encoding='gbk')asf:2old_data=f.read().split('\n')3delold_data[0]4#四舍五入得到新数据5new_data=[]6foriinrange(len(old_data)):7ifeval(ol......
  • 实验5 文件应用编程
    实验任务61withopen('data6.csv','r',encoding='gbk')asf:2old_data=f.read().split('\n')3delold_data[0]45new_data=[]6foriinrange(len(old_data)):7ifeval(old_data[i])+float(0.5)......
  • 实验5
    task6.py源代码:1withopen('data6.csv','r',encoding='gbk')asf:2data1=f.read().split('\n')3deldata1[0]4print('原始数据:')5print(data1)67foriinrange(len(data1)):8data1[i]......