python学习实例(6)

举报
兔老大 发表于 2021/04/21 23:38:00 2021/04/21
【摘要】 #=============================#6.6 文件系统(File System)#============================= #+++++++++++++++++++++++++++++#6.6.3 Python中的文件操作#+++++++++++++++++++++++++++++ #<程序:读取文件os.py>f = o...

  
  1. #=============================
  2. #6.6 文件系统(File System)
  3. #=============================
  4. #+++++++++++++++++++++++++++++
  5. #6.6.3 Python中的文件操作
  6. #+++++++++++++++++++++++++++++
  7. #<程序:读取文件os.py>
  8. f = open("./Task1.txt",'r'); fls = f.readlines()
  9. for line in fls:
  10. line = line.strip(); print (line)
  11. f.close()
  12. #<程序:读取文件os.py,计算并写回>
  13. f = open("./Task1.txt",'r+'); fls = f.readlines()
  14. for line in fls:
  15. line = line.strip(); lstr = line.split()
  16. if lstr[0] == '3':
  17. res = 0
  18. for e in lstr[1:]:
  19. res+=int(e)
  20. f.write('\n4 '+str(res)); f.close()
  21. #+++++++++++++++++++++++++++++
  22. #6.6.4 学生实例4.6.3扩展
  23. #+++++++++++++++++++++++++++++
  24. #<程序:存储考试结果到class1.txt文件>
  25. class student:
  26. def __init__ (self,mname,studentID):
  27. self.name = mname; self.StuID = studentID; self.Course_Grade = {};
  28. self.Course_ID = []; self.GPA = 0; self.Credit = 0
  29. def selectCourse(self,CourseName,CourseID):
  30. self.Course_Grade[CourseID]=0; #CourseID:0 加入字典
  31. self.Course_ID.append(CourseID) # CourseID 加入列表
  32. self.Credit = self.Credit+ CourseDict[CourseID].Credit #总学分数更新
  33. def getInfo(self):
  34. print("Name:",self.name);print("StudentID",self.StuID);print("Course:")
  35. for courseID,grade in self.Course_Grade.items():
  36. print(CourseDict[courseID].courseName,grade)
  37. print("GPA",self.GPA); print("Credit",self.Credit); print("")
  38. def TakeExam(self, CourseID):
  39. self.Course_Grade[CourseID]=random.randint(50,100)
  40. self.calculateGPA()
  41. def Grade2GPA(self,grade):
  42. if(grade>=90):
  43. return 4
  44. elif(grade>=80):
  45. return 3
  46. elif(grade>=70):
  47. return 2
  48. elif(grade>=60):
  49. return 1
  50. else:
  51. return 0
  52. def calculateGPA(self):
  53. g = 0;
  54. #遍历每一门所修的课程
  55. for courseID,grade in self.Course_Grade.items():
  56. g = g + self.Grade2GPA(grade)* CourseDict[courseID].Credit
  57. self.GPA = round(g/self.Credit,2)
  58. class Course:
  59. def __init__ (self,cid,mname,CourseCredit,FinalDate):
  60. self.courseID = cid
  61. self.courseName = mname
  62. self.studentID = []
  63. self.Credit = CourseCredit
  64. self.ExamDate = FinalDate
  65. def SelectThisCourse(self,stuID): #记录谁修了这门课,在studentID列表里
  66. self.studentID.append(stuID)
  67. def setupCourse (CourseDict): #建立CourseList: list of Course objects
  68. CourseDict[1]=Course(1,"Introducation to Computer Science",4,1)
  69. CourseDict[2]=Course(2,"Advanced Mathematics",5,2)
  70. CourseDict[3]=Course(3,"Python",3,3)
  71. CourseDict[4]=Course(4,"College English",4,4)
  72. CourseDict[5]=Course(5,"Linear Algebra",3,5)
  73. def setupClass (StudentDict): #输入一个空列表
  74. NameList = ["Aaron","Abraham","Andy","Benson","Bill","Brent","Chris","Daniel",
  75. "Edward","Evan","Francis","Howard","James","Kenneth","Norma","Ophelia","Pearl",
  76. "Phoenix","Prima","XiaoMing"]
  77. stuid = 1
  78. for name in NameList:
  79. StudentDict [stuid]=student(name,stuid) #student对象的字典
  80. stuid = stuid + 1
  81. def SelectCourse (StudentList, CourseList):
  82. for stu in StudentList: #每一个学生修几门课
  83. CourseNum = random.randint(3,len(CourseList)) #修CourseNum数量的课
  84. #随机选,返回列表
  85. CourseIndex = random.sample(range(len(CourseList)), CourseNum)
  86. for index in CourseIndex:
  87. stu.selectCourse(CourseList[index].courseName,CourseList[index].Credit)
  88. CourseList[index].SelectThisCourse(stu.StuID)
  89. def ExamSimulation (StudentList, CourseList):
  90. for day in range(1,6): #Simulate the date
  91. for cour in CourseList:
  92. if(cour.ExamDate==day): # Hold the exam of course on that day
  93. for stuID in cour.studentID:
  94. for stu in StudentList:
  95. if(stu.StuID == stuID): #student stuID selected this course
  96. stu.TakeExam(cour.courseID)
  97. import random
  98. CourseDict={}
  99. StudentDict={}
  100. setupCourse(CourseDict)
  101. setupClass(StudentDict)
  102. SelectCourse(list(StudentDict.values()),list(CourseDict.values()))
  103. ExamSimulation(list(StudentDict.values()),list(CourseDict.values()))
  104. SaveToFile = ["ID"," ","Name"," ","Credit"," ","GPA","\n"]
  105. for stu in StudentDict.values():
  106. SaveToFile.append(str(stu.StuID))
  107. SaveToFile.append(" ")
  108. SaveToFile.append(str(stu.name))
  109. SaveToFile.append(" ")
  110. SaveToFile.append(str(stu.Credit))
  111. SaveToFile.append(" ")
  112. SaveToFile.append(str(stu.GPA))
  113. SaveToFile.append("\n")
  114. f = open("class1.txt","w")
  115. f.writelines(SaveToFile)
  116. f.close()
  117. #<程序:查询文件class1.txt中满足某条件的学生信息>
  118. def select(path,col,op,val):
  119. f = open(path,"r")
  120. colNum = 0
  121. if col == "ID": colNum = 0
  122. elif col == "Name": colNum = 1
  123. elif col == "Credit": colNum = 2
  124. elif col == "GPA": colNum = 3
  125. f.readline()
  126. Info = f.readlines()
  127. res = []
  128. for e in Info:
  129. e = e.strip()
  130. eList = e.split()
  131. if colNum != 1:
  132. exp = eList[colNum] + op + val
  133. else:
  134. exp = "'" + eList[colNum] + "'" + op + "'" + val + "'"
  135. if eval(exp):
  136. res.append(e)
  137. f.close()
  138. return res
  139. for e in select("class1.txt","Credit",">=","15"):
  140. print (e)
  141. #<程序:对文件class1.txt中学生进行排序>
  142. def sort(path,col,direct):
  143. #direct表示排序方向,">"为从大到小排序,"<"相反。
  144. colNum = 0
  145. if col == "Credit": colNum = 2
  146. elif col == "GPA": colNum = 3
  147. ifrev = False
  148. if direct == ">":ifrev = True
  149. f = open(path,"r")
  150. f.readline()
  151. Info = f.readlines()
  152. res = []
  153. for e in Info:
  154. eList = e.split()
  155. res.append(eList)
  156. res =sorted(res, key=lambda res: res[colNum],reverse=ifrev)
  157. #第三个参数为排序方向
  158. f.close()
  159. return res
  160. L = [('b',2),('a',1),('c',3),('d',4)]
  161. print (sorted(L, key=lambda x:x[1]))

 

文章来源: fantianzuo.blog.csdn.net,作者:兔老大RabbitMQ,版权归原作者所有,如需转载,请联系作者。

原文链接:fantianzuo.blog.csdn.net/article/details/83025226

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。