Python:7-3 统计单词数-应用 (10分)

在需要统计若干段文字(英文)中的单词数量,并且还需统计每个单词出现的次数。 注1:单词之间以空格(1个或多个空格)为间隔。 注2:忽略空行或者空格行。

要求:

统计前,需要从文字中删除指定标点符号!.,??#和0至9的数字。 注意:所谓的删除,就是用1个空格替换掉相应字符。 统计单词时需要忽略单词的大小写。 单词个数为0时。只需显示“0”。

输入格式:

若干行英文,最后以%%%为结束。。

输出格式:

单词数量 出现次数排名前6的单词(次数按照降序排序,如果次数相同,则按照键值的字母升序排序)及出现次数。

输入样例:

在这里给出一组输入。例如:

Failure is probably The fortification in your pole!

It#is like a1 peek your wallet as the thief when You
are thinking how2 to. spend several hard-won lepta.

when yoU are? wondering whether new money it#has laid
background Because of: yOu5?, then at the6 heart of the
Tom say: Who is the best? No one dare to say yes.
most lax alert and! most low awareness and* left it
%%%
godsend failed it is
!!!

输出样例:

在这里给出相应的输出。例如:

52
the=5
is=3
it=3
you=3
and=2
are=2
代码实现:

words = ""
while True:
    a = input()
    if a == "%%%":
        break
    a = a.lower()
    for i in "!.,:*?#012345689":
        a = a.replace(i, ' ')
    words = words + " " + a
words = words.split()
s = {}
for i in words:
    if i in s:
        s[i] += 1
    else:
        s[i] = 1
s = list(s.items())
s.sort(key = lambda x:x[0])
s.sort(key = lambda x:x[1], reverse = True)
print(len(s))
for i in range(6):
    word,count = s[i]
    print("{}={}".format(word, count))

版权声明:本文为qq_37689422原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。