实验5 文件应用编程

#task3
with open('data3.txt','r',encoding='utf-8')as f1:
    with open('data3_processed.txt','w',encoding='utf-8')as f2:
        a=f1.read().split('\n')
        a.pop(0)
        c=[]
        d=[eval(i) for i in a]
        for i in a:
            x=eval(i)
            if x-int(x)<0.5:
                c.append(int(eval(i)))
            else:
                c.append(int(eval(i))+1)
        d2=[int(i)for i in c]
        f2.write(f'原始数据\t四舍五入后的数据\n')
        for i in range(len(d)):
            f2.write(f'{d[i]}\t\t{d2[i]}\n')
print(f'原始数据:\n{d}\n四舍五入后的数据:\n{c}')

#task4
with open('data4.txt','r',encoding='utf-8') as f:
    data=f.readlines()
    data.remove(data[0])
    x0=[]
    for i in data:
        a=i.split()
        x0.append(a)
    x1=sorted(x0,key=(lambda x:x[2]))
    x2=[x1[i] for i in range(0,8)]
    x3=sorted(x2,key=(lambda x:x[3]),reverse=True)
    x4=[x1[i] for i in range(8,10)]
    x5=sorted(x4,key=(lambda x:x[3]),reverse=True)
    y=x3+x5

    y1=[]
    for i in y:
        b='\t'.join(i)
        b=b+'\n'
        y1.append(b)
    y1.insert(0,'学号\t姓名\t专业\t分数\n')
    for i in y1:
        print(i)
with open('data4_processed.txt','w',encoding='utf-8')  as f:
    for i in y1:
        f.write(i)

#task5
with open('data5.txt','r',encoding='utf-8')as f:
    with open('data5_with_line.txt', 'w', encoding='utf-8') as f1:
        a=f.read().strip('\n')
        b = len(a.splitlines())
        print('行数:', b)
        c = len(a.split())
        print('单词数:', c)
        d = 0
        for i in a:
            if i == ' ':
                d += 1
        print('空格数:', d)
        e = 0
        for e, number in enumerate(a):
            e += 1
        print('字符数:', e)
        a=a.split('\n')
        n='\n'.join(a)
        for i in range(len(a)):
            f1.write(f'{i+1}.{a[i]}\n')

 

posted @ 2022-05-16 23:54  孙艺欣  阅读(16)  评论(2编辑  收藏  举报