中国大学MOOCPython语言程序设计基础学习笔记和课后练习第7周(南京邮电大学)

前情提要

1.中国大学MOOCPython语言程序设计基础学习笔记和课后练习1-4周(南京邮电大学)

2.中国大学MOOCPython语言程序设计基础学习笔记和课后练习5-6周(南京邮电大学)

第7周 异常处理和文件操作

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
代码:

try:
    a,b=input("请输入被除数和除数,用空格分割:").split()
    a=eval(a)
    b=eval(b)
    print("{}/{}={}".format(a,b,a/b))
except ZeroDivisionError:
    print("很抱歉,程序产生错误了!错误原因是:除数不能为0!")
except ValueError:
    print("很抱歉,程序产生错误了!错误原因是:没有输入足够的参数!")
finally:
    print("这里包含的程序将负责善后工作。")
import turtle
def drawstar(x,y,color):
    turtle.up()
    turtle.goto(x,y)
    turtle.down()
    turtle.color(color)
    for i in [0,1,2,3,4]:
        turtle.right(144)
        turtle.forward(100)

#请进小海龟,并设置小海龟的外形和颜色
from fivestar import drawstar
import turtle
turtle.shape("turtle")
turtle.color("red")
        
#绘制第一个五角星
drawstar(-200,200,"blue")
#绘制第二个五角星
drawstar(300,200,"green")
#继续设置小海龟的位置和朝向,并绘制第三、第四个五角星
drawstar(-200,-200,"red")
drawstar(300,-200,"yellow")
#送小海龟回家
turtle.up()
turtle.home()

else的用法:
在这里插入图片描述
两种排序方式,sorted不改变原来的值而sort改变
在这里插入图片描述

单元作业

1.有两个磁盘文件A.txt和B.txt,各存放一行字符(请同学们将A.txt和B.txt放在和程序相同的文件夹中,并自行在其中添加一行字符),要求把这两个文件中的信息合并(按字母顺序重新排列,忽略大小写),并输出到一个新文件C.txt中。

#异常处理模块
try:
    #打开文件
    with open('A.txt','r') as file:
        text1=file.read()
        lst1=[]
        #除去非字母内容,默认本次练习只按照英文字母排序
        for i in text1:
            if 'a'<=i<='z' or 'A'<=i<='Z':
                lst1.append(i)
    with open('B.txt', 'r') as file:
        text2 = file.read()
        lst2 = []
        # 除去非字母内容,默认本次练习只按照英文字母排序
        for i in text2:
            if 'a' <= i <= 'z' or 'A' <= i <= 'Z':
                lst2.append(i)
    #把这两个文件中的信息合并
    textC=lst1+lst2
    #按字母顺序重新排列,忽略大小写
    textC=sorted(textC,key=lambda x:x.lower())
    textC=''.join(textC)
    #保存到C.txt文件中
    with open('C.txt','w') as fout:
        fout.write(textC)
except:
    print('无法打开文件。')

2.附件中包含一篇英文小短文,请编写程序统计这篇小短文中每一个英文字母出现的次数,并将每个字母出现的次数添加至该文本的最后。

#2.附件中包含一篇英文小短文,请编写程序统计这篇小短文中每一个英文字母出现的次数,并将每个字母出现的次数添加至该文本的最后。
try:
    #读取短文
    with open('Beauty.txt','r') as fin:
        file=fin.read()
    #统计次数并保存到文件最后
    result={}
    #遍历文本每一个字符并把次数统计保存为字典中的值
    for i in file:
        if 'A'<=i.upper()<='Z':
            #使用get方法避免不存在报错的情况,第二个参数表明该键不存在
            result[i.upper()]=result.get(i.upper(),0)+1
    #我写的排序方法
    '''
    lst=list(result.items())
    lst.sort(key=lambda x:x[1])
    for key,item in lst:
        print(key,':',item)
        
    #老师的排序方法更简洁
    for key in sorted(result.keys()):
        print(key,':',result[key])
    '''
    #添加到文件最后
    with open('Beauty.txt','a') as fin:
        # for key in sorted(result.keys()):
        #     #print(key,'的出现次数:',result[key])
        #     fin.write('\n'+key+'的出现次数:'+str(result[key]))
        #或者写成
        for key in sorted(result.keys()):
            fin.write('\n{}出现的次数为:{}'.format(key,(result[key])))
except Exception as e:
    print(e)

第7周实验周

Python中字符串的使用方法参考:
https://www.runoob.com/python/python-strings.html
Python中列表的使用方法参考:
https://www.runoob.com/python/python-lists.html
Python中元组的使用方法参考:
https://www.runoob.com/python/python-tuples.html
Python中字典的使用方法参考:
https://www.runoob.com/python/python-dictionary.html
Python中集合的使用方法参考:
https://jingyan.baidu.com/article/1974b2896ba089f4b1f774a4.html
Python中文件的使用方法参考:
https://www.yiibai.com/python3/python_files_io.html

1.请编写Python程序完成以下要求:当前工作目录下有一个文件名为class_score.txt的文本文件,存放着某班学生的姓名(第1列)、数学课成绩(第2列)和语文课成绩(第3列),每列数据用制表符(\t)进行分隔。

在这里插入图片描述
我的代码:

# -*- coding: utf-8-*-
#函数1:
#分别求这个班数学和语文的平均分(保留1位小数)并输出
def average_Info(count):
    Math_sum=0
    Chinese_sum=0
    for i in count:
        Math_sum+=int(count[i][0])
        Chinese_sum+=int(count[i][1])
    Math_average =Math_sum/len(count)
    Chinese_average =Chinese_sum/len(count)
    return 'Math_average:%.1f,Chinese_average:%.1f'%(Math_average,Chinese_average)

#函数2:
#找出两门课都不及格(<60)的学生,输出他们的姓名和各科成绩
def Grade_Info(count):
    for i in count:
        if int(count[i][0])<60 and int(count[i][1])<60:
            print('name:%s,Math_grade:%s,Chinese_grade:%s'%(i,count[i][0],count[i][1]))

#函数3:
#找出两门课的平均分在90分以上的学生,输出他们的学号和各科成绩,由于本题没给出学号,因此按照上题做法输出姓名和各科成绩吧,
#也可以重新建立字典,键为学号,值为姓名和成绩。
def func(count):
    #两门课平均分
    grade_sum=0
    for i in count:
        grade_sum+=(int(count[i][0])+int(count[i][1]))
        if grade_sum>90*2:
            print('name:%s,Math_grade:%d,Chinese_grade:%d' % (i, int(count[i][0]), int(count[i][1])))
        grade_sum = 0

if __name__=='__main__':
    #读取文件内容并存放入字典中
    with open('class_score.txt','r',encoding='utf-8') as file:
        t=file.readlines()
        count={}
        for line in t:
            line.replace('\t',"")
            line=line.split()
            count[line[0]]=(line[1],line[2])
    print('number1:',average_Info(count))
    print('number2:')
    Grade_Info(count)
    print('number3:')
    func(count)

输出结果:
number1: Math_average:80.8,Chinese_average:76.0
number2:
name:朱莉莉,Math_grade:56,Chinese_grade:36
number3:
name:林晓晓,Math_grade:95,Chinese_grade:98

2.请编写Python程序完成以下要求:编写程序制作英文学习词典,词典有三个基本功能:添加、查询和退出。程序读取源文件路径下的txt格式词典文件,若没有就创建一个。词典文件存储方式为:“英文单词 中文释义”(英文单词和中文释义之间用空格分割)且每行仅有一对中英释义。程序会根据用户的选择进入相应的功能模块,并显示相应的操作提示。当添加的单词已存在时,显示“该单词已添加到字典库”;当查询的单词不存在时,显示“字典库中未找到这个单词”。用户输入其他选项时,提示“输入有误”。

# -*- coding: gbk *-
#英文词典
try:
    with open('cidian.txt', 'r', encoding='gbk') as file:
        t = file.readlines()
        count = {}
        for line in t:
            line=line.strip('\n')
            line=line.split()
            count[line[0]]=line[1]
        #构建一个字典,读取文件内容并存入
        #print(count)
    while True:
        s=input("请输入你想要的口令(添加、查询和退出):")
        if s=='添加':
            t=input('请输入想添加的单词:')
            if t in count.keys():
                print('该单词已添加到字典库')
            else:
                count[t]=input('请输入想添加单词的释疑:')
                print('添加单词成功')

        elif s=='查询':
            t = input('请输入想查询的单词:')
            if t in count.keys():
                print(count[t])
            else:
                print('字典库中未找到这个单词')
        elif s=='退出':
            break
        else:
            print('输入有误')

except Exception as e:
    print('出错原因:',e)
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐