实验5 文件应用编程

task3.py

file1=open('D://data3.txt','r',encoding='utf-8')
ls1=[]
ls=[]
ls2=[]
d1=file1.readlines()
for i in d1[1:]:
    i=i.strip('\n')
    ls1.append(i)
print(f'原始数据:')
print(ls1)

for x in d1[1:]:
    x=x.strip('\n')
    b=float(x)
    y=b-int(b)
    if y>=0.5:
        x_int=int(b)+1
    else:
        x_int=int(b)
    ls.append(x_int)
ls.insert(0,'四舍五入后数据')
print(ls[0])
print(ls[1:])
    
file1.close()


for k in range(len(d1)):
    ls2.append(str(d1[k])+'\t'*3+str(ls[k])+'\n')
               
with open('D:\\data3_processed.txt','w',encoding='utf-8') as f:
    f.writelines(ls2)
        

task4.py

with open('D:\\data4.txt','r',encoding='utf-8') as f:
    d1=f.readlines()
d2=[]
for line in d1[1:]:
    line=line.split()
    line=list(line)
    d2.append(line)
for i in range(len(d2)):
    d2[i]=tuple(d2[i])
d3=sorted(d2,key=lambda x:(x[2],-int(x[3])))
d4=[]
for j in range(len(d3)):
    d4.append(d3[j][0]+'\t'+d3[j][1]+'\t'+d3[j][2]+'\t'+d3[j][3]+'\n')

with open('D:\\data4_processed.txt','w',encoding='utf-8') as f:
    f.write('学号'+'\t'+'姓名'+'\t'+'专业'+'\t'+'分数'+'\n')
    f.writelines(d4)


with open('D:\\data4_processed.txt','r',encoding='utf-8') as f:
    l=f.readlines()
for line in l:
    line=line.strip('\n')
    print(line)

task5.py

 

with open('D:\\data5.txt','r',encoding='utf-8') as f:
    d1=f.readlines()
d2=[line.split() for line in d1]
word_count=0
line_count=0
character_count=0
c=[]
for line in d1:
    word=line.split()
    line_count+=1
    word_count+=len(word)
    character_count+=len(line)
    for i in line:
        if i==' ':
            c.append(i)
print(f'行数:{line_count}')
print(f'单词数:{word_count}')
print(f'空格数:{len(c)}')
print(f'字符数:{character_count}')

with open('D:\\data5_with_line.txt','w',encoding='utf-8') as f:
    for i in range(len(d2)):
        t=i+1
        s=''.join(d2[i])
        f.write(str(t)+' '+s+'\n')

 

posted @ 2022-05-16 21:59  星标g  阅读(11)  评论(3编辑  收藏  举报