首页 > 其他分享 >实验5

实验5

时间:2023-06-07 11:22:31浏览次数:26  
标签:encoding random lst 实验 print txt open

task6

源代码:

import csv

title = ['原始数据', '四舍五入后的数据']

lst = []
yuan_lst = []
hou_lst = []
with open('data6.csv', 'r') as f:
    read_lst = f.readlines()
    for i in range(1, len(read_lst)):
        y = float(read_lst[i].strip('\n'))
        yuan_lst.append(y)
        c = int(y+0.5)
        hou_lst.append(c)
        lst.append([y, c])

print(f'{title[0]}:\n{yuan_lst}')
print(f'{title[1]}:\n{hou_lst}')

with open('data6_processed.csv', 'w', encoding='gbk', newline='')as f:
    f_writer = csv.writer(f)
    f_writer.writerow(title)
    f_writer.writerows(lst)

实验结果:

 

task7

源代码:

with open('data7.csv','r',encoding='gbk') as f:
    data1 = f.read().split('\n')
del data1[0]
lsta = []
lstm = []
for i in data1:
    lst1 = i.split(',')
    if lst1[2] == 'Acting':
        lsta.append(lst1)
    else:lstm.append(lst1)
lstm.sort(key=lambda x:x[-1],reverse = True)
lsta.sort(key=lambda x:x[-1],reverse = True)
info = lsta + lstm
title = ['学号','姓名','专业','分数']
with open('data7_processed.csv','w',encoding='gbk') as f:
    f.write(','.join(title)+'\n')
    for items in info:
        f.write(','.join(items)+'\n')
print('{:<10}'.format(title[0]),'{:<10}'.format(title[1]),'{:<10}'.format(title[2]),'{:<15}'.format(title[3]))
for i in info:
    print('{:<10}'.format(i[0]),'{:<10}'.format(i[1]),'{:<10}'.format(i[2]),'{:<15}'.format(i[3]))

实验结果:

 

task8

源代码:

lines = 0
words = 0
sum1 = 0
space = 0
with open('hamlet.txt','r',encoding='utf-8') as f:
    for line in f:
        word = line.split()
        lines += 1
        words += len(word)
        sum1 += len(line)
        for i in line:
            if i == ' ':
                space += 1
            else:
                pass
print('hamlet.txt粗滤统计:')
print(f'行数:{lines}')
print(f'单词数:{words}')
print(f'字符数:{sum1}')
print(f'空格数:{space}')

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

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

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

实验结果:

 

task9

源代码:

def is_valid(sfz):
    if len(sfz) != 18:
        return False
    elif (sfz[:-1].isnumeric() and sfz[-1] == 'X') or sfz.isnumeric():
        return True
    else:return False


with open('data9_id.txt','r',encoding='utf-8') as f:
    data = f.read().split('\n')
del data[0]
data2 = []
data3 =[]
print('姓名,出生日期,年龄')
for i in data:
    lst = i.split(',')
    data2.append(lst)
lst2 = []
for i in data2:
    if is_valid(i[1]) == True:
        name = i[0]
        btd = i[1][6:14]
        age = str(2023 - int(i[1][6:10]))
        lst2.append([name,btd,age])
lst2.sort(key=lambda x:x[2],reverse=True)
for i in lst2:
    print(i[

实验结果:

 

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)

实验结果:

 

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

实验结果:

 

OVER.

 

标签:encoding,random,lst,实验,print,txt,open
From: https://www.cnblogs.com/khyyyds/p/17462817.html

相关文章

  • 实验7 面向对象编程与内置模块
    实验任务1task1.py1classAccount:23def__init__(self,name,account_number,initial_amount=10):4self._name=name5self._card_no=account_number6self._balance=initial_amount7defdeposit(self,amount):......
  • 实验五 文件应用编程
    task6实验源码1importcsv23title=['原始数据','四舍五入后的数据']45lst=[]6yuan_lst=[]7hou_lst=[]8withopen('data6.csv','r')asf:9read_lst=f.readlines()10foriinrange(1,len(read_l......
  • 实验5
    task61importcsv2title=[]3info=[]45withopen('data6.csv','r',encoding='gbk')asf:6f_reader=csv.reader(f)7forlineinf_reader:8info.append(line)9x=info.pop(0)10title.appe......
  • 实验五
    任务6:withopen('data6.csv','r',encoding='gbk')asf:data=list(f.readlines())data=[i.strip('\n')foriindata]importdecimaldecimal.getcontext().rounding='ROUND_HALF_UP'title=[data[0......
  • 实验5
    实验源码:withopen('data6.csv','r',encoding='gbk')asf:data=list(f.readlines())data=[i.strip('\n')foriindata]importdecimaldecimal.getcontext().rounding='ROUND_HALF_UP'title=[data[......
  • 实验7 面向对象编程与内置模块
    一、实验结论:1.实验任务1:task1.py程序源码:1'''2银行账户3数据:持卡人姓名、账号、当前余额4操作:取款、存款、打印账户信息、返回账户余额5'''67classAccount:8'''一个模拟银行账户的简单类'''910def__init__(self,name,account_nu......
  • 实验五
    实验任务6task6.py1withopen('data6.csv','r',encoding='gbk')asf:2old_data=f.read().split('\n')3delold_data[0]4processed_data=[]5foriinrange(len(old_data)):6ifeval(old_data[i])......
  • 实验六
    实验任务1-1实验源码1fromturtleimport*2defmove(x,y):3penup()4goto(x,y)5pendown()6defdraw(n,size=100):7foriinrange(n):8fd(size)9left(360/n)10defmain():11pensize(2)12pencolo......
  • 实验五 文件应用编程
    task6.py1withopen('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])7......
  • 实验6
    1.实验任务1task1_1.py程序源代码:fromturtleimport*defmove(x,y):'''画笔移动到坐标(x,y)处'''penup()goto(x,y)pendown()defdraw(n,size=100):'''绘制边长为size的正n变形'''foriinran......