【问题描述】
给定一段英文文章,编写程序统计出现次数最多的单词,并将文章中的所有该单词改写为全大写字母。单词之间使用空格或标点符号隔开,单词连写,如“is't”,看作一个单词。
·输入数据:
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.
·输出结果:
统计结果:[(the',6)]
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.
【解题思路J
首先将所有的单词按空格、标点分割构成列表,随后将列表中的单词全部转换为小写。统
计列表中单词的频数,并将结果保存在一个字典中,然后将字典转化为列表并从大到小排序,
输出的第一个元素为出现次数最多的单词。接下来,使用re.sub()方法将出现次数最多的单词
替换为全大写字母。
【程序代码】
import re
s=input(请输入一段英文:)
pattern re.compile(r"[\w']+")
words [w.lower()for w in pattern.split(s)if len(w.strip())>O]
wordNum
for w in words:
if w in wordNum.keys():
wordNum[w]+=1
else:
wordNum[w]=1
items list(wordNum items())
items.sort(key=lambda x:x[1],reverse=True)
print(数单:', items[이])
pattern1 items[O][O]
rpl pattern1.upper()
pattern1 r'\b'+pattern1+r'\b'
ss re.sub(pattern1,rpl,s,count=0,flags=re.I)
print(ss)