溴麝香草酚狼 2022-05-29 08:47 采纳率: 100%
浏览 47
已结题

元音字母出现次数最多的单词的词频统计

问题

问题是这样的,一个词频统计的练习

img

相关代码
def get_txt():
    txt = open('sentence.txt','rt').read()
    txt = txt.lower()
    return txt
s_txt = get_txt()
wordset = s_txt.split()
yalp = ['a','e','i','o','u']
counts = {}
for word in wordset:
    for alp in word:
        if alp in yalp:
            counts[word] =counts.get(word,0) + 1
        items = list(counts.items())
        items.sort(key = lambda x:x[1],reverse = False)
        for i in range(5):
            word ,counts = items[i]
            print('{0:<10}{1:>5}'.format(word ,counts))
运行结果及报错内容
Traceback (most recent call last):
    word ,counts = items[i]
IndexError: list index out of range
only          1

我想要达到的结果

运行结果却报错了,上网搜了一圈仍然没有解决,可以帮忙看看吗
另外
1.对于下面这行有更优化的方法吗(感觉很蠢)

for word in wordset:
    for alp in word:
        if alp in yalp:

2.这行是抄的,对于为什么lambda要这么用不是很理解

 items.sort(key = lambda x:x[1],reverse = False)

求解答!

  • 写回答

2条回答 默认 最新

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

    要把items排序的部分移到循环外面,不然字典都还没做好呢。而且题目要逆序输出,sort里面的reverse应该为True

    wordset = s_txt.split()
    yalp = ['a','e','i','o','u']
    counts = {}
    for word in wordset:
        for alp in word:
            if alp in yalp:
                counts[word] =counts.get(word,0) + 1
    items = list(counts.items())
    items.sort(key = lambda x:x[1],reverse = True)
    for i in range(5):
        word ,counts = items[i]
        print('{0:<10}{1:>5}'.format(word ,counts))
    

    lambda就是为了省事,没什么特别的,不然key关键字后面要跟一个函数,你也可以自定义成这样:

    def fun(x):
      return (x[1])
    items.sort(key = fun,reverse = True)
    

    看格式也能知道lambda是怎么写的了吧。
    至于你说的优化代码部分,可以考虑把所有元音字母转换成数字1,然后统计每个单词里的1的数量

    yalp = {ord('a'):ord('1'),ord('e'):ord('1'),ord('i'):ord('1'),ord('o'):ord('1'),ord('u'):ord('1')}
    counts = {}
    for word in wordset:
        a = word.translate(yalp)
        counts[word] =a.count('1')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

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

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分