&给你 2021-11-04 09:06 采纳率: 66.7%
浏览 95
已结题

用python统计英语单词出现的次数,并实现输出结果的美化

编写程序,统计下面英文短文中,每个单词出现的次数。其他要求:(1)忽略大小写;(2)去除标点符号,不能在单词中出现标点或出现对标点的统计;(3)按词频由高到低的顺序输出统计结果,每个词及其统计结果显示时固定宽度并右对齐,每行显示5个单词的统计结果。
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.

  • 写回答

1条回答 默认 最新

  • Fioman_Hammer 2021-11-04 09:12
    关注
    
    article = """
    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.
    """
    import string
    
    data = article.lower().strip()
    for c in string.punctuation:
        data = data.replace(c," ") # 将标点符号转换成空格
    # 将换行符替换为空格
    data = data.replace("\n"," ")
    words = data.strip().split(" ")
    wordDict = {}
    for word in words:
        if word == "" or word == " ":
            continue
        if word not in wordDict:
            wordDict[word] = 1
        else:
            wordDict[word] = wordDict[word] + 1
    
    # 对字典,按照value进行排序
    resSorted = sorted(wordDict.items(),key=lambda x:x[1],reverse=True)
    
    # 先求出单词的最大长度,按照这个最大的长度去定每个单词的位置
    maxLen = len(max(wordDict.keys(),key=lambda x:len(x))) # 固定宽度按照最长的那个单词去定
    
    start = 0
    for word,count in resSorted:
        if start % 5 == 0 and start != 0:
            print()
        print("{:>{}} {}".format(word,maxLen,count),end=" ")
        start += 1
    

    结果:

    img

    如果觉得答案对你有帮助,请点击下采纳,谢谢~

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 11月4日
  • 已采纳回答 11月4日
  • 创建了问题 11月4日

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)