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

实验五 文件应用编程

时间:2023-06-05 23:13:27浏览次数:36  
标签:文件 old data1 data 编程 实验 print open append

实验任务6

 1 # 读取并处理原始数据with open('data6.csv','r',encoding = 'gbk') as f:
 2     old_data = f.read().split('\n')
 3 del old_data[0]
 4 #  四舍五入得到新数据
 5 new_data = []
 6 for i in range(len(old_data)):
 7     if eval(old_data[i]) + float(0.5) >= int(eval(old_data[i])) + 1:
 8         new_data.append(str(int(eval(old_data[i]))+1))
 9     else:
10         new_data.append(str(int(eval(old_data[i]))))
11 # 形成二维列表
12 title = ['原始数据','四舍五入后数据']
13 data = []
14 for i in range(len(old_data)):
15     data.append([old_data[i],new_data[i]])
16 # 写入
17 with open('data6.csv','w',encoding = 'gbk') as f:
18     f.write(','.join(title) + '\n')
19     for i in data:
20         f.write(','.join(i) + '\n')
21 print('原始数据:')print(old_data)print('四舍五入后数据:')print(new_data)
View Code

 

 实验任务7

 1 with open('data7.csv','r',encoding='gbk') as f:
 2     data1 = f.read().split('\n')
 3 del data1[0]
 4 lsta = []
 5 lstm = []
 6 for i in data1:
 7     lst1 = i.split(',')
 8     if lst1[2] == 'Acting':
 9         lsta.append(lst1)
10     else:lstm.append(lst1)
11 lstm.sort(key=lambda x:x[-1],reverse = True)
12 lsta.sort(key=lambda x:x[-1],reverse = True)
13 info = lsta + lstm
14 title = ['学号','姓名','专业','分数']
15 with open('data7_processed.csv','w',encoding='utf-8') as f:
16     f.write(','.join(title)+'\n')
17     for items in info:
18         f.write(','.join(items)+'\n')
19 print('{:<10}'.format(title[0]),'{:<10}'.format(title[1]),'{:<10}'.format(title[2]),'{:<15}'.format(title[3]))
20 for i in info:
21     print('{:<10}'.format(i[0]),'{:<10}'.format(i[1]),'{:<10}'.format(i[2]),'{:<15}'.format(i[3]))
View Code

 实验任务8

 1 with open(r'C:\Users\28678\Downloads\实验5数据文件\hamlet.txt','r') as f:
 2     data=f.read()
 3 
 4 print('hamlet.txt粗略统计:')
 5 print(f'行数:{len(data.splitlines())}')
 6 print(f'单词数:{len(data.split())}')
 7 print(f'字符数:{len(data)}')
 8 print(f'空格数:{data.count(" ")}')
 9 
10 data1=data.splitlines()
11 data2=[]
12 for i in range(len(data1)):
13     data2.append(f'{i+1} '+data1[i]+'\n')
14 
15 with open(r'C:\Users\28678\Downloads\实验5数据文件\hamlet_with_line_number.txt',
16 'w') as f:
17     f.writelines(data2)
View Code

 实验任务9

 1 def is_valid(sfz):
 2     if len(sfz) != 18:
 3         return False
 4     elif (sfz[:-1].isnumeric() and sfz[-1] == 'X') or sfz.isnumeric():
 5         return True
 6     else:return False
 7 
 8 
 9 with open('data9_id.txt','r',encoding='utf-8') as f:
10     data = f.read().split('\n')
11 del data[0]
12 data2 = []
13 data3 =[]
14 print('姓名,出生日期,年龄')
15 for i in data:
16     lst = i.split(',')
17     data2.append(lst)
18 lst2 = []
19 for i in data2:
20     if is_valid(i[1]) == True:
21         name = i[0]
22         btd = i[1][6:14]
23         age = str(2023 - int(i[1][6:10]))
24         lst2.append([name,btd,age])
25 lst2.sort(key=lambda x:x[2],reverse=True)
26 for i in lst2:
27     print(i[0],end=',')
28     print(f'{i[1][:4]}-{i[1][4:6]}-{i[1][6:8]}',end=',')
29     print(i[2])
View Code

 实验任务10

task10-1

 1 with open(r'C:\Users\28678\Downloads\实验5数据文件\data10_stu.txt','r') as f:
 2     data=f.readlines()
 3 
 4 data0=[i.strip('\n').split('\t') for i in data]
 5 
 6 import random
 7 n=eval(input('输入随机抽点人数:'))
 8 data1=random.sample(data0,n)
 9 for i in data1:
10     print(' '.join(i))
11 
12 import datetime
13 t=datetime.datetime.now()
14 fn=t.strftime('%Y%m%d')
15 
16 with open(r'C:\Users\28678\Downloads\实验5数据文件\{}.txt'.format(fn),'w') as f:
17     for i in data1:
18         i[0]+='\t'
19         i[1]+='\t'
20         i[2]+='\n'
21         f.writelines(i)
View Code

 

task10-2

 1 import datetime
 2 t = datetime.datetime.now()
 3 filename = t.strftime('%Y%m%d') + '.txt'
 4 start='抽取开始'
 5 print(start.center(50,'*'))
 6 with open('data10_stu.txt', 'r', encoding='utf-8') as f:
 7     data = f.readlines()
 8 
 9 def random_selection(n):
10     import random
11     demo = random.sample(data, n)
12     return demo
13 selection=set()
14 numbers=[]
15 
16 while True:
17     n = eval(input('输入随机抽点人数:'))
18     if n != 0:
19         x=random_selection(n)
20         for i in x:
21             print(i)
22             data.remove(i)
23             with open(filename,'a',encoding='utf-8') as f :
24                 f.writelines(i)
25     else:
26         print('抽取结束'.center(50,'*'))
27         break
View Code

 

 

标签:文件,old,data1,data,编程,实验,print,open,append
From: https://www.cnblogs.com/202280060019x/p/17459198.html

相关文章

  • 实验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]......
  • linux 下文件的权限
                     ......
  • 实验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)......
  • 实验6
    1、实验任务1task1_1.py实验源码:1fromturtleimport*23defmove(x,y):4penup()5goto(x,y)6pendown()78defdraw(n,size=100):9foriinrange(n):10fd(size)11left(360/n)1213defmain():14pens......
  • C# 异步编程
     基于Task的异步编程模式(TAP)是Microsoft为.Net平台下使用Task进行编程所提供的一组建议,这种模式提供了可以被await消耗(调用)方法的APIs,并且当使用async关键字编写遵守这种模式的方法时,手写Task通常很有用。通常TAP用起来与普通方式没什么两样,但是不支持ref和out参数。   任务......
  • 异步编程async体会
    namespace异步编程{classProgram{staticvoidMain(string[]args){Console.WriteLine("mianthisisasync{0}",Thread.CurrentThread.ManagedThreadId);Do();......
  • Golang高性能编程--slice的学习总结
    在go语言中,数组变量属于值类型,因此当一个数组变量被复制或者传递时,实际上会复制整个数组。eg,将a赋值给b,修改a中的元素,并不会修改b中的元素。为了避免复制数组,一般会传递指向数组的指针。packagemainimport"fmt"funcmain(){ a:=[...]int{1,2,3} b:=a a[0]=100......
  • 实验5 文件应用编程
    task6.py1withopen('data6.csv','r',encoding='gbk')asf:2data=list(f.readlines())3data=[i.strip('\n')foriindata]45importdecimal6decimal.getcontext().rounding='ROUND_HALF_UP'7......
  • C语言编程语法—输入与输出
    当我们提到输入时,这意味着要向程序填充一些数据。输入可以是以文件的形式或从命令行中进行。C语言提供了一系列内置的函数来读取给定的输入,并根据需要填充到程序中。当我们提到输出时,这意味着要在屏幕上、打印机上或任意文件中显示一些数据。C语言提供了一系列内置的函数来输出数......