2、 实验内容:文本文件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
我的代码:
vowel="aeiouAEIOU" #里面的字母都是元音
with open('sentence.txt','r',encoding='utf-8') as f: #1 以只读取模式读取记事本文件gdpython4.txt(读取文本时不自动把\r\n转换成\n)
words_file=words_flie.lower() #2
words=words_file.split(" ") #3句子中单词之间以空格分割,提取单词
words = list(set(words))
dict1={}
for word in words:
count = 0
for i in word:
if a == list(filter(lambda x:x in 'aeiou',word)) : #4
count+=1
counts[word] = len(a) #5在字典中更新保存元音字母个数
item= list(counts.items()) #6
item.sort(key=lambda x:x[1], reverse=True) #7 对单词中含有元音字母个数进行递减排序
for j in range(3):
word,number = item[j]
print("{:<17}(){}".format(word,count)) #8 输出时含有元音字母的单词靠左排列,占17位
如何改善此代码