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

实验5 文件应用编程

时间:2023-06-05 23:12:09浏览次数:35  
标签:文件 old encoding open 编程 实验 print new data

实验任务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('原始数据:')
22 print(old_data)
23 print('四舍五入后数据:')
24 print(new_data)

实验任务7

 1 with open('data7.csv','r',encoding='gbk')as f:
 2     title=[f.readline()]
 3     data=f.readlines()
 4 def getscore(ls):
 5     return ls[len(ls)-1]
 6 
 7 data=[line.strip('\n').split(',')for line in data]
 8 
 9 data.sort(key=lambda x:(x[2],-int(x[3])))
10 
11 
12 with open('data7_processed.csv', 'w', encoding = 'gbk') as f:
13     f.write(','.join(title))
14     for item in data:
15         f.write(','.join(item) + '\n')
16 title=title[0].strip('\n').split(',')
17 
18 print('{:<10}'.format(title[0]),'{:<10}'.format(title[1]),'{:<10}'.format(title[2]),'{:<15}'.format(title[3]))
19 for i in data:
20     print('{:<10}'.format(i[0]), '{:<10}'.format(i[1]), '{:<10}'.format(i[2]), '{:<10}'.format(i[3]))

实验任务8

 1 with open('hamlet.txt','r',encoding='utf-8')as f:
 2     data=f.readlines()
 3     print('行数:',len(data))
 4 
 5 x=''
 6 for line in data:
 7     x+=line
 8 alpha=0
 9 b=0
10 for i in x:
11     if i.isalpha():
12         alpha+=1
13     else:
14         b+=1
15 
16 word=len(x.split())
17 print('字符数:',alpha+b)
18 print('单词数:',word)
19 print('空格数:',x.count(' '))
20 data = [line.strip('\n').split(',') for line in data]
21 with open('hamlet_with_line_number','w',encoding='utf-8') as f:
22     for i,j in enumerate(data,start=1):
23         j=j[0]
24         f.write("{}{}{}".format(i,' ',j)+'\n')

实验任务9

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[0],end=',')
    print(f'{i[1][:4]}-{i[1][4:6]}-{i[1][6:8]}',end=',')
    print(i[2])

实验任务10

task10_1

 1 import datetime
 2 t = datetime.datetime.now()
 3 filename = t.strftime('%Y%m%d') + '.txt'
 4 n=eval(input('输入随机抽取人数:'))
 5 with open('data10_stu.txt', 'r', encoding = 'utf-8') as f:
 6     data=f.readlines()
 7 
 8 
 9 def random_selection(n):
10     import random
11     demo = random.sample(data, n)
12     return demo
13 x=random_selection(n)
14 for i in x :
15     print(i)

task10_2

 1 with open('data10_stu.txt','r',encoding='utf-8') as f:
 2     data = f.readlines()
 3 print('{:*^40}'.format('抽点开始'))
 4 n = int(input('输入随机抽点人数:'))
 5 import random
 6 x = []
 7 sum1 = 0
 8 x2 = ''
 9 while n != 0:
10     counts = 0
11     while counts < n:
12         new = random.randint(0, len(data) - 1)
13         if new in x:
14             new = random.randint(0, len(data) - 1)
15         else:
16             counts +=1
17             x.append(new)
18     for i in range(sum1,sum1+n):
19         print(data[x[i]])
20         x2 += data[x[i]]
21     sum1 += n
22     n = int(input('输入随机抽点人数:'))
23 
24 with open('20230602.txt','w',encoding='utf-8') as f:
25     f.writelines(x2)
26 
27 print('{:*^40}'.format('抽点结束'))

 

标签:文件,old,encoding,open,编程,实验,print,new,data
From: https://www.cnblogs.com/xixihamugua/p/17459227.html

相关文章

  • 实验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语言提供了一系列内置的函数来输出数......
  • 用c实现:编译出来的可执行文件运行完成后删除自己
    没办法。可执行文件和bat脚本文件不一样,它运行时会被加锁,无法获取写权限。原由:因为每次编译一个c文件后都会生成一个exe文件,占用了我的视野资源,所以我每次都要定期运行一个批处理脚本来清理这些文件。于是我就想,exe文件自己不是也有运行权限吗,它能不能自己获取自己的写权限在执行......