- 统计文件中大写字母出现的次数
任务描述
本关任务:编写程序,统计一个文本文件中出现的大写字母和它们出现的次数,并输出.
相关知识
为了完成本关任务,你需要掌握:1.读文本文件,2.字典操作,3.列表操作,4.字符串操作。
编程要求
根据提示,在右侧编辑器补充代码,输出文件中出现的大写字母以及它们出现的次数。
测试说明
平台会对你编写的代码进行测试:
测试输入:test.txt;
预期输出:
(‘A’, 8)
(‘B’, 6)
(‘P’, 2)
(‘L’, 1)
(‘E’, 1)
(‘C’, 1)
测试输入:dream.txt;
预期输出:
(‘I’, 3)
(‘D’, 2)
(‘G’, 1)
#统计大写字母出现的次数,并按照字母出现次数降序排序输出
def countchar(file):
# *************begin************#
txt = open(file,"r")
i = 0
count = {}
words = txt.read()
for word in words:
if word in count:
count[word] +=1
else:
if word >= 'A' and word <= 'Z':
count[word]=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)
- 统计文件中单词出现的次数,并输出出现次数高的前三个单词
任务描述
本关任务:编写程序,统计一个文件中单词出现的次数,并输出出现次数最多的前3个单词。
相关知识
为了完成本关任务,你需要掌握:1.读取文件,2.字典操作,3.列表操作,4.字符串操作。
编程要求
根据提示,在右侧编辑器补充代码,输出出现次数最多的前三个单词。
测试说明
平台会对你编写的代码进行测试:
测试输入:dream.txt;
预期输出:
(7, ‘the’)
(7, ‘of’)
(4, ‘will’)
测试输入:test.txt;
预期输出:
(4, ‘Apple’)
(3, ‘Blue’)
(2, ‘Big’)
#统计一个文件中单词出现的次数,并输出出现次数最多的前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)