7-1 jmu-Java&Python-统计文字中的单词数量并按出现次数排序

7-1 jmu-Java&Python-统计文字中的单词数量并按出现次数排序

分数 12
作者 郑如滨
单位 集美大学
现在需要统计若干段文字(英文)中的单词数量,并且还需统计每个单词出现的次数。

注1:单词之间以空格(1个或多个空格)为间隔。
注2:忽略空行或者空格行。

基本版:
统计时,区分字母大小写,且不删除指定标点符号。

进阶版:

统计前,需要从文字中删除指定标点符号!.,😗?。 注意:所谓的删除,就是用1个空格替换掉相应字符。
统计单词时需要忽略单词的大小写。
输入说明
若干行英文,最后以!!!!!为结束。

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

输入样例1

failure is probably the fortification in your pole

it is like a peek your wallet as the thief when you
are thinking how to spend several hard-won lepta
          
when you are wondering whether new money it has laid
background because of you then at the heart of the
     
most lax alert and most low awareness and left it

godsend failed
!!!!!

输出样例1

46
the=4
it=3
you=3
and=2
are=2
is=2
most=2
of=2
when=2
your=2

输入样例2

Failure is probably The fortification in your pole!

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

when yoU are? wondering whether new money it has laid
background Because of: yOu?, then at the 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
!!!!!

输出样例2

54
the=5
is=3
it=3
you=3
and=2
are=2
most=2
of=2
say=2
to=2

代码长度限制
16 KB
时间限制
1600 ms
内存限制
180 MB

解题思路

本题我分为五部分来设计,分别是:

  1. 用户输入
  2. 数据预处理
  3. 统计
  4. 排序
  5. 打印

由于本题步骤稍多,对此我用面对对象的方式,来分模块处理,但思路上还是面向过程的,这样写的好处就是代码复用度更高,写法和代码风格更加固定。
这五个步骤均较为简单,值得注意的是排序的时候,最大优先级按值进行排序并且是降序,次优先级是按键排序,并且是升序,此时自定义函数比较麻烦和复杂,需要用到sorted函数,它的第二个参数key,可以自定义一个函数进行排序指定字段优先级的返回,完整代码如下,供参考:

class TextCount:
    def __init__(self):
        self.msg = str()
        self.items = {}
        self.remove = ['!', '.', ',', ':', '*', '?']

        while 1:
            line = input()
            if line == '!!!!!':
                break
            else:
                self.msg += '\n' + line

    def __str__(self):
        self.run()
        msg = ["%d" % len(set(self.msg.split()))]
        times = 0
        for item in self.items:
            times += 1
            msg.append(f"{item[0]}={item[1]}")
            if times == 10:
                break
        return "\n".join(msg)

    def delete(self, msg: str, str: str):
        return msg.replace(str, '')

    def pretreatment(self):
        self.msg = self.msg.lower()
        self.msg = self.msg.replace('\n', ' ')
        for i in self.remove:
            self.msg = self.delete(self.msg, i)

    def count(self):
        for i in self.msg.split():
            if i in self.items:
                self.items[i] += 1
            else:
                self.items[i] = 1

    def sort(self):
        self.items = sorted(self.items.items(), key=lambda item: (-item[1], item[0]))

    def run(self):
        self.pretreatment()
        self.count()
        self.sort()


if __name__ == '__main__':
    result = TextCount()
    print(result)

posted @ 2022-11-22 14:03  蠢蛋快跑  阅读(603)  评论(0)    收藏  举报