实验五 文件应用编程

task_3

with open('data3.txt','r+',encoding='utf-8')as f:
    a=[]
    for i in f:
        i=i.strip('\n')
        a.append(i)
a.pop(0)
b=[eval(i) for i in a]
print(f'原始数据:\n{b}')
c=[round(eval(i)) for i in a]
print(f'四舍五入后数据:\n{c}')
with open('data3_processed.txt','w',encoding='utf-8')as f:
    w1=['原始数据']+[str(i) for i in a]
    w2=['四舍五入后数据']+[str(i) for i in c]
    for i in range(len(a)):
        f.write(f'{w1[i]}\t{w2[i]}\n')

 

 task_4

with open('data4.txt','r+',encoding='utf-8')as f:
    a=[i.strip('\n').split('\t') for i in f]
    b=a.pop(0)
    a.sort(key=lambda x:(x[2],-int(x[-1])))
    print('\t'.join(b))
    for i in a:
        print('\t'.join(i))
with open('data4.1.txt','w',encoding='utf-8')as f:
    f.write('\t'.join(b)+'\n')
    for i in a:
        f.write('\t'.join(i)+'\n')

 

 

task_5

with open("data5.txt", "r", encoding="utf-8") as f:
    d = f.readlines()
line = 1
word = 0
spa = 0
cha = 0
for i in d:
    if i != "\n":
        i1 = i.split()
        for i2 in i1:
            word += 1
    for j in i:
        cha += 1
        if j == '\n':
            line += 1
        if j == " ":
            spa += 1
print(f"行数:{line}")
print(f"单词数:{word}")
print(f"空格数:{spa}")
print(f"字符数:{cha}")

 

 实验总结:

python好难,完全做不到灵活运用

posted on 2022-05-16 23:03  写作业的xzy  阅读(10)  评论(3编辑  收藏  举报