当前位置:   article > 正文

头歌:Python开发技术—文件和异常1(答案)【第1关:统计文件中大写字母出现的次数 + 第2关:统计文件中单词出现的次数,并输出出现次数高的前三个单词】_第1关:统计文件中大写字母出现的次数

第1关:统计文件中大写字母出现的次数

目录

第1关:统计文件中大写字母出现的次数

第2关:统计文件中单词出现的次数,并输出出现次数高的前三个单词

第1关:统计文件中大写字母出现的次数

  1. #统计大写字母出现的次数,并按照字母出现次数降序排序输出
  2. def countchar(file):
  3. # *************begin************#
  4. txt = open(file,"r")#file字符串
  5. i=0
  6. count={}#空字典
  7. words = txt.read() #文件内容读入words当中
  8. for word in words: #挨个读取words中内容
  9. if word in count: #word 在字典中
  10. count[word] +=1 #字母前进
  11. else: #word 不在字典中
  12. if word>='A' and word <= "Z":
  13. count[word] = 1 #置1
  14. result = sorted(count.items(),key = lambda word:word[1],reverse=True)
  15. for i in range(len(result)):
  16. print(result[i])
  17. # **************end*************#
  18. file = input()
  19. countchar(file)

第2关:统计文件中单词出现的次数,并输出出现次数高的前三个单词

 

  1. #统计一个文件中单词出现的次数,并输出出现次数最多的前3个单词
  2. def countword(file):
  3. txt = open(file,"r")
  4. words =txt.read()
  5. for i in '",-:,.':
  6. words = words.replace(i," ")
  7. words = words.split()
  8. count = {}
  9. for word in words:
  10. count[word]=count.get(word,0)+1
  11. result = sorted(count.items(),key=lambda word:word[1],reverse=True)
  12. for i in range(3):
  13. print(result[i][::-1])
  14. file = input()
  15. countword(file)

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/380861
推荐阅读
相关标签
  

闽ICP备14008679号