编程语言
首页 > 编程语言> > 同济大学Python程序设计基础 实验七:文件

同济大学Python程序设计基础 实验七:文件

作者:互联网

同济大学Python程序设计基础

实验七

第一题

打开一个文本文件T1.txt。读出文件的内容,然后进行如下处理:
①统计并且输出文件的行数;
②将文件的大小写字母互相转换后写入文件T2.txt,即大写的转成小写的,小写的转换成大写的,其余不变

代码片.

 f1=open('T1.txt','r')
f2=open('T2.txt','w')
lines=f1.readlines()
hang=len(lines)
print(lines)
print(hang)
new=[]
for line  in lines:
    newline=""
    for ch in line:
        if 'A'<=ch<'Z':
            ch=chr(ord(ch)+ord('a')-ord('A'))
        elif 'a'<=ch<'z':
            ch=chr(ord(ch)+ord('A')-ord('a'))
        newline=newline+ch
    new.append(newline)
print(new)
f2.writelines(new)
f1.close()
f2.close()

第二题

打开如下图2.7.1所示的学生成绩文件.txt,统计平均分、最低分、平均分、最高分。

在这里插入图片描述

代码片.

f1=open('学生成绩文件.txt','r')
stu=f1.readlines()
score=[]
for s in stu:
    m=s.split(" ")
    score.append(int(m[2]))
print(score)
ma=max(score)
mi=min(score)
s=sum(score)
avg=s/len(score)
print (ma)
print (mi)
print (s)
print (avg)

第三题

从互联网上下载《红楼梦》的某一回组成文本文件hlm.txt,然后设计一程序统计林黛玉和贾宝玉两个人名在文件中出现的次数。

代码片.

import jieba
f1=open('T1.txt','r')
s=f1.readlines();
print(s)
st=jieba.lcut(s[0])
print(st)
lin=0
jia=0
for word in st:
    if word=='林黛玉' :
        lin=lin+1
    elif word=='贾宝玉':
        jia=jia+1
print(lin)
print(jia)

第四题

编写一个职工奖金处理程序。要求如下:
①输入不超过10个职工的工号、姓名和奖金,保存在文件JJ.txt。文件中的数据格式:
90813,张大海,1080.50元
②从JJ.txt中读出数据,然后按奖金从低到高排序,保存在文件NewJJ.txt

代码片.

f1=open('JJ.txt','w')
s=input("请输入职工的工号、姓名和奖金(格式:工号,姓名,奖金):")
cnt=1
while s!="" and cnt<10:
    cnt+=1
    f1.write(s+'\n')
    s=input()
f1.close()

f1=open('JJ.txt','r')
f2=open('NewJJ.txt','w')
data=f1.readlines()
workers=[]
for worker in data:
    w=worker.split(',')
    workers.append(w)
    
for i in range(len(workers)):
    workers[i][2]=int(workers[i][2])

w=sorted(workers,key=lambda x:x[2],reverse=False)
for line in w:
    s=""
    for word in line:
        s=s+","+str(word)
    s=s[1:]
    f2.writelines(s+"\n")
        
f1.close()
f2.close()

第五题

编写一个将两个文本文件的内容合并的程序。

代码片.

f1=open('1.txt','r')
f2=open('2.txt','r')
f3=open('3.txt','w')

s1=f1.readlines()
s2=f2.readlines()
s=s1[0]+s2[0]
f3.write(s)
f1.close()
f2.close()
f3.close()
        

标签:f1,文件,Python,同济大学,score,print,程序设计,txt,open
来源: https://blog.csdn.net/cjzui6666/article/details/112384455