实验五

#task3.py
with open('data3.txt', 'r', encoding='utf-8') as f:
    data = f.read().strip()
    a = data.split('\n')
    y = a.pop(0)
    b = []
    for i in a:
        x = eval(i)
        if x-int(x) < 0.5:
            b.append(int(eval(i)))
        elif 0.5 <= x-int(x):
            b.append(int(eval(i))+1)
    with open('data3_processed.txt', 'w', encoding='utf-8') as g:
        g.write('{:<10} {:>10}\n'.format(y, '四舍五入后的数据'))
        for i in range(len(a)):
            g.write('{:<14}{:>5}\n'.format(a[i], b[i]))
print(f'原始数据:\n{a}\n四舍五入后的数据:\n{b}')

 

 

 

 

#task4.py
with open('data4.txt', 'r', encoding='utf-8') as f:
    data = f.read().strip('\n')
    a = data.split('\n')
    m = a.pop(0)
    x = []
    for i in a:
        a = i.split('\t')
        x.append(a)
    y = sorted(x, key=lambda x:(x[2], x[3]), reverse=True)
    with open('data4_processed.txt', 'w', encoding='utf-8') as g:
        g.write(m + '\n')
        print(m)
        for n in y:
            g.write('\t'.join(n))
            g.write('\n')
            print('\t'.join(n))

 

 

 

 

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

 

 

 

posted @ 2022-05-17 13:10  bamboosama  阅读(7)  评论(3编辑  收藏  举报