赞
踩
目录
第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)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。