溴麝香草酚狼 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日

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)