二1- 2022-06-03 20:52 采纳率: 60%
浏览 178
已结题

如何打印英文元音单词

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位

如何改善此代码

  • 写回答

1条回答 默认 最新

  • 请叫我问哥 Python领域新星创作者 2022-06-03 21:28
    关注

    修改了你的代码:

    with open('sentence.txt','r',encoding='utf-8') as f: #1 以只读取模式读取记事本文件gdpython4.txt(读取文本时不自动把\r\n转换成\n)
        words_file = f.read()
    words=set(words_file.lower().split()) #3句子中单词之间以空格分割,提取单词
    dict1={}
    for word in words:
        a = list(filter(lambda x:x in 'aeiou',word)) 
        dict1[word] = len(a) #5在字典中更新保存元音字母个数
    res = sorted(dict1.items(), key=lambda x:x[1], reverse=True) #7 对单词中含有元音字母个数进行递减排序
    for i, j in res:
        print("{:<17}{}".format(i, j)) #8 输出时含有元音字母的单词靠左排列,占17位
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 6月11日
  • 已采纳回答 6月3日
  • 创建了问题 6月3日

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?