在英语中英文单词组成句子,在键盘上输入一句含有标点英文语句,统计其中最长的单词以及各单词出现的次数。具体要求如下:
(1) 用户输入一个英文语句,英文语句子中要包含标点符号;若个别单词后面带有标点符号,其标点符号不能计算为单词;
(2) 输出英文语句中最长的单词,若有多个单词,则每行输出一个;
(3) 统计各单词出现的次数,按照数量从多到少排列在屏幕上输出;如果出现的数量相同,则按照单词在句子中的顺序进行显示;输出的格式为:单词左对齐,宽度为10。
例如,如果用户在键盘上输入句子:Hi, we play on the Maldive beach on October the second. 则输出如下图所示:
import string
import re
P = string.punctuation
d = dict()
s = 'Hi, we play on the Maldive beach on October the second.'
patt = f'[{P}]'
res = re.sub(patt, '', s)
res = res.split()
for i,v in enumerate(res):
if v not in d:
d[v] = [i,len(v), 1]
else:
d[v] = [i,len(v), d[v][2] +1]
d1 = sorted(d.items(), key =lambda x: [len(x[0]), -x[1][0]], reverse = True)
d2 = sorted(d.items(), key = lambda x: [x[1][2], -x[1][0]], reverse = True)
m = d1[0][1][1]
for k, v in d1:
if v[1] == m:
print(f'maxlen:{v[1]:<3}word:{k:<5}')
for k, v in d2:
print(f'{k:<10}{v[2]:->5}')
--result
maxlen:7 word:Maldive
maxlen:7 word:October
on ----2
the ----2
Hi ----1
we ----1
play ----1
Maldive ----1
beach ----1
October ----1
second ----1