将文章中出现次数最多的单词改为全大写 【问题描述】  给定一段英文文章,编写程序统计出现次数最多的单词,并将文章中的所有该单词改写为全大写字母。单词之间使用空格或标点符号隔开,单词连写,如“is�

将文章中出现次数最多的单词改为全大写

【问题描述】Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

给定一段英文文章,编写程序统计出现次数最多的单词,并将文章中的所有该单词改写为全大写字母。单词之间使用空格或标点符号隔开,单词连写,如“is't”,看作一个单词。Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

·输入数据:Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

The wind carries the house for miles and miles.Now Dorothy can stand up becausehe house isn't spinning any more.The cyclone had set the house down very gently in themidst of a country of great beauty.There were lovely patches of greensward all about,with stately trees bearing rich fruits.Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

·输出结果:Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

统计结果:[(the',6)]Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

THE wind carries THE house for miles and miles.Now Dorothy can stand up becauseTHE house isn't spinning any more.THE cyclone had set THE house down very gentlyin THE midst of a country of great beauty.There were lovely patches of greensward allabout,with stately trees bearing rich fruits.Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

【解题思路JKye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

首先将所有的单词按空格、标点分割构成列表,随后将列表中的单词全部转换为小写。统Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

计列表中单词的频数,并将结果保存在一个字典中,然后将字典转化为列表并从大到小排序,Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

输出的第一个元素为出现次数最多的单词。接下来,使用re.sub()方法将出现次数最多的单词Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

替换为全大写字母。Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

【程序代码】Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

import reKye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

s=input(请输入一段英文:)Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

pattern re.compile(r"[\w']+")Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

words [w.lower()for w in pattern.split(s)if len(w.strip())>O]Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

wordNumKye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

for w in words:Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

if w in wordNum.keys():Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

wordNum[w]+=1Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

else:Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

wordNum[w]=1Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

items list(wordNum items())Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

items.sort(key=lambda x:x[1],reverse=True)Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

print(数单:', items[이])Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

pattern1 items[O][O]Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

rpl pattern1.upper()Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

pattern1 r'\b'+pattern1+r'\b'Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

ss re.sub(pattern1,rpl,s,count=0,flags=re.I)Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

print(ss)Kye100150满分答卷(100150.com)-青少年编程等级考试及竞赛题库

关 键 词

将文章中出现次数最多的单词改为全大写

相关教程

提示声明

  • 免责声明:本站资源均来自网络或者用户投稿,仅供用于学习和交流:如有侵权联系删除!

猜你喜欢