m0_67028936 2022-05-29 10:46 采纳率: 100%
浏览 214
已结题

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))

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

  • 写回答

2条回答 默认 最新

  • 请叫我问哥 Python领域新星创作者 2022-05-29 11:10
    关注

    因为你现在是把‘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))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

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

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大