&给你 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 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭