用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.


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

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