m0_64542878 2022-10-21 22:01 采纳率: 85.7%
浏览 81
已结题

python实现词频统计问题

编写程序,统计下面英文短文中,每个单词出现的次数。其他要求:(1)忽略大小写;(2)去除标点符号,不能在单词中出现标点或出现对标点的统计;(3)按词频由高到低的顺序输出统计结果,每个词及其统计结果显示时固定宽度并右对齐,每行显示5个单词的统计结果,总体要求整齐,方便查看,参考代码行数:35行
文章:
In our world , one creature without any rivals is a lifeless creature. If a man lives without rivals, he is bound to be satisfied with the present and will not strive for the better. He would hold back before all difficulties and decline in inaction and laziness. Adverse environment tends to cultivate successful people. Therefore, your rivals are not your opponents or those you grudge. Instead , they are your good friends! In our lives, we need some rivals to "push us into the river", leaving us striving ahead in all difficulties and competitions. In our work, we need some rivals to be picky about us and supervise our work with rigorous requirements and standards. Due to our rivals, we can bring out our potential to the best; Due to our rivals, we will continuously promote our capabilities when competing with them!
预期效果:

img

  • 写回答

4条回答 默认 最新

  • 游一游走一走 2022-10-21 22:54
    关注
    import re
    
    data = 'In our world , one creature without any rivals is a lifeless creature. If a man lives without rivals, he is bound to be satisfied with the present and will not strive for the better. He would hold back before all difficulties and decline in inaction and laziness. Adverse environment tends to cultivate successful people. Therefore, your rivals are not your opponents or those you grudge. Instead , they are your good friends! In our lives, we need some rivals to "push us into the river", leaving us striving ahead in all difficulties and competitions. In our work, we need some rivals to be picky about us and supervise our work with rigorous requirements and standards. Due to our rivals, we can bring out our potential to the best; Due to our rivals, we will continuously promote our capabilities when competing with them!'
    data = data.lower()
    
    rule = re.compile("[^a-zA-Z]")
    data = rule.sub(' ', data)
    setWords = data.split(' ')
    result = {}
    for item in setWords:
        if item == ' ' or item == '':
            continue
        result[item] = result.get(item, 0) + 1
    
    result = sorted(result.items(), key=lambda x: x[1], reverse=True)
    
    for index, item in enumerate(result, 1):
        print('{}->{}'.format(item[0].rjust(20, ' '), item[1]), end='')
        if index % 5 == 0:
            print()
    

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 10月30日
  • 已采纳回答 10月22日
  • 创建了问题 10月21日