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

该代码示例展示了两个Python函数,分别用于统计文件中大写字母出现的次数并按降序排列,以及计算文件中单词的出现频率并输出前三。这两个功能都涉及到文本分析和数据排序。
摘要由CSDN通过智能技术生成

目录

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

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

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

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


file = input()
countchar(file)

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

 

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


file = input()
countword(file)

 

  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值