首页 > 其他分享 >实验五

实验五

时间:2023-06-07 09:46:29浏览次数:33  
标签:open encoding data1 datetime 实验 print data

任务6:

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:
         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_processed.csv','w',encoding='gbk',newline='') as f :
     f_writer=csv.writer(f)
     f_writer.writerow(title)
     f_writer.writerows(data_new)

运行结果:

 

 

任务7:

with open('data7.csv','r',encoding = 'gbk') as f:
    data = f.readlines()
data_t = ['学号','姓名','专业','分数']
data1 = [i.strip('\n').split(',') for i in data]
data1.remove(data1[0])

data2=sorted(data1,key=lambda x:(x[2],-int(x[3])))
with open('data7_processed.csv','w',encoding = 'gbk') as f:
    f.write(','.join(data_t) + '\n')
    for item in data2:
        f.write(','.join(item) + '\n')

print(f'{"学号":10s}{"姓名":10s}{"专业":10s}{"分数":10s}')
for a,b,c,d in data2:
    print('{:<10s}{:<10s}{:<10s}{:<10}'.format(a,b,c,d))

运行结果:

 

 

任务八:

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)

运行结果:

 

 任务九:

import datetime


def is_valid(x):
    if len(x) == 18 and x[:-1].isdigit() and (x[-1].isdigit() or x[-1] == 'X'):
        return True
    else:
        return False


with open('data9_id.txt', 'r', encoding='utf-8') as f:
    data0 = f.readlines()
    title = data0.pop(0)

data0 = [i.strip('\n').split(',') for i in data0]

data1 = []
for i in data0:
    if is_valid(i[1]):
        data1.append(i)
print(data1)

t = datetime.datetime.now()
y = t.strftime('%Y%m%d')
for i in data1:
    age = str(int(y)-int(i[1][6:14]))
    i.append(age[:2])
    i[1] = i[1][6:10] + '-' + i[1][10:12] + '-' + i[1][12:14]
data2 = sorted(data1, key=lambda x: -int(x[2]))

print('姓名, 出生日期, 年龄')
for i in data2:
    print(', '.join(i))

运行结果:

 

任务10-1:

import random
import datetime

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

data0 = [i.strip('\n').split('\t') for i in data]
n = eval(input('输入随机抽点人数:'))
data1 = random.sample(data0, n)

for i in data1:
    print('  '.join(i))

t = datetime.datetime.now()
title = t.strftime('%Y%m%d')

with open(f'{title}.txt', 'w', encoding='utf-8') as f:
    for i in data1:
        f.write(f'{i[0]}\t{i[1]:6s}\t{i[2]:10s}\n')

运行结果:

 

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

运行结果:

 

标签:open,encoding,data1,datetime,实验,print,data
From: https://www.cnblogs.com/e2718281/p/17462153.html

相关文章

  • 实验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......
  • 实验6 turtle绘图与python库应用编程体验
    实验任务1task1_.py实验源码:fromturtleimport*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(-20......
  • 实验5
    task6源码:importcsvwithopen('data6.csv','r',encoding='gbk')asf:data_o=f.readlines()foriinrange(len(data_o)):data_o[i]=data_o[i].strip('\n')#原始数据deldata_o[0]#处理后数据data_1=[]ford_......
  • 实验五 文件应用编程
    实验五 文件应用编程 实验任务六程序源代码: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......