python词频统计探讨题

题目:文本文件sentence.txt中保存一句英文(不含标点符号),请把还有元音字母的个数最多的前三个英文单词打印出来,并按要求输出。具体要求入下。
(1)以只读方式读取文本文件sentence.txt
(2)句子中单词之间以空格分割。
(3)对单词中含有元音字母个数进行递减排序
(4)输出含有超过2个元音字母的单词;
(5)输出时含有元音字母的单词靠左排列,占17位

示例:sentence.txt中句子如下
Only once in a lifetime that a special dream comes suddenly your entire world seems beautiful and new

输出:
beautiful 5
lifetime 4
special 3
entire 3

我写的代码:
#e10.1CalHamlet.py
def getText():
txt=open('sentence.txt','r').read()
txt=txt.lower()
return txt
hamletTxt=getText()
words=hamletTxt.split()
counts={}
letter='aeiou'
for word in words:
if letter in word:
counts[word] = counts.get(word,0) +1
items=list(counts.items())
items.sort(key=lambda x:x[1], reverse=True)
for i in range(4):
word,count=items[i]
print('{0:<17}'.format(word,count))

我的疑惑点: 怎么对单词中的元音字母个数进行统计并输出单词呢
还有最后两行的报错要怎么修改鸭
各位朋友们 一起探讨吧

因为你现在是把‘aeiou’当成一个完整的字符串去检查,当然什么也找不到,所以字典是空的,最后当然会报错了。
只要改后面的部分就可以了:

counts={}
for word in words:
    a = list(filter(lambda x:x in 'aeiou',word))
    counts[word] = len(a)
items=list(counts.items())
items.sort(key=lambda x:x[1], reverse=True)
for i in range(4):
    word,count=items[i]
    print('{0:<17}{1}'.format(word,count))
with open('sentence.txt','r') as f:
    data = f.read()  #一次读出全部文本
 
words = sum([w.split() for w in data.split('\n')],[])  #取出所有单词,这样写法支持多行文本文件
 
words = [i.lower() for i in words]  #大写字母转小写,如Only 和 only算同一单词就需要这一行
 
dic = { w:sum(int(i in 'aeiou') for i in w) for w in words } # 单词:元音数 为键值对组成字典
 
dic = dict(sorted(dic.items(), key=lambda x:x[1], reverse=True)) #排序
 
for k,v in dic.items():  #遍历字典占位17长度输出
    if v>2:
        print(f'{k:<17}{v}')