任务3

with open('C:\\Users\\肖鑫\\Desktop\\实验5数据文件\\实验5数据文件\\data3.txt','r+',encoding='utf-8') as f:
    data = f.readlines()
data0 = [line.split() for line in data[1:]]
data1 = [float(line[0]) for line in data0]
data2 = []
for i in range(len(data1)):
    a = data1[i]
    if a-int(a)<0.5:
        a=int(a)
        data2.append(a)
    else:
        a=int(a)+1
        data2.append(a)
print('原始数据\n',data1,'\n四舍五入后数据\n',data2)
with open('C:\\Users\\肖鑫\\Desktop\\实验5数据文件\\实验5数据文件\\data3.txt','w',encoding='utf-8') as f:
    write1 = ['原始数据'] + [str(i) for i in data1]
    write2 = ['四舍五入后的数据'] + [str(i) for i in data2]
    for i in range(len(data)):
        f.write(f"{write1[i]}\t{write2[i]}\n")

 

 任务4

with open('C:\\Users\\肖鑫\\Desktop\\实验5数据文件\\实验5数据文件\\data4.txt','r+',encoding='utf-8') as f:
    str=[i.strip('\n').split('\t') for i in f]
    a=str.pop(0)
    str.sort(key=lambda x : (x[2],-int(x[-1])))
    print('\t'.join(a))
    for i in str:
        print('\t'.join(i))
with open('C:\\Users\\肖鑫\\Desktop\\实验5数据文件\\实验5数据文件\\data4.txt','w',encoding='utf-8') as f:
    f.write('\t'.join(a))
    f.write('\n')
    for i in str:
        f.write('\t'.join(i))
        f.write('\n')

 

 任务5

with open('C:\\Users\\肖鑫\\Desktop\\实验5数据文件\\实验5数据文件\\data5.txt', 'r',encoding = 'utf-8') as f:
    b=f.readlines()
with open('C:\\Users\\肖鑫\\Desktop\\实验5数据文件\\实验5数据文件\\data5.txt', 'r',encoding = 'utf-8')as f:
    a=f.read()
    kong=a.count(' ')
    words=a.split()
print(f'行数:{len(b)}')
print(f'单词数:{len(words)}')
print(f'空格数:{kong}')
print(f'字符数:{len(a)}')

with open('C:\\Users\\肖鑫\\Desktop\\实验5数据文件\\实验5数据文件\\data5.txt', 'w',encoding = 'utf-8') as f:
    x=1
    for i in b:
        i=str(x)+' '+i
        f.write(i)
        x+=1

 

posted on 2022-05-17 14:30  清橙往忆  阅读(5)  评论(2编辑  收藏  举报