python实现简单的统计

实现功能如下:

对于一串给定的纯数字字符串,实现统计相邻的相同数字,用中文输出,如下:、
输入:'11223345'   		输出:2个一,2个二,2个三,1个四,1一五
输入:'11223345112233'     输出:2个一,2个二,2个三,1个四,1个五,2个一,2个二,2个三 

代码:

class MyClass:
    # 初始化数据,count用来记录相邻的数字相同次数
    def __init__(self, inp_str, count=1):
        self.inp_str = inp_str
        self.count = count
	
    def func_count(self):
        len_test = len(self.inp_str) - 1
        cursor = 0  # 定义一个游标
        while cursor < len_test:
            if self.inp_str[cursor] == self.inp_str[cursor + 1]:
                self.count += 1  # 如果相邻两数等同,count加一
            else:
                # 如果相邻两数不同,输出
                chinese_num = self.take_chinese(self.inp_str[cursor])
                print(f'{self.count}个{chinese_num}', end=',')
                self.count = 1
            cursor += 1
        else:
            res = self.take_chinese(self.inp_str[cursor])
            print(f'{self.count}个{res}', end=' ')
            
	# 寻找数字对应的中文
    def take_chinese(self, num):
        # list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        # list2 = ['一', '二', '三', '四', '五', '六', '七', '八', '九']
        # for index, v in enumerate(list1):
        #     if num == str(v):
        #         return list2[index]
        number_dic = {
            '1':'一','2':'二','3':'三','4':'四','5':'五','6':'六','7':'七','8':'八','9':'九',
        }
        return number_dic[num]



teststr = input("输入要计数的字符串:").strip()
obj = MyClass(teststr)
obj.func_count()
posted @ 2020-12-02 20:00  王寄鱼  阅读(595)  评论(0编辑  收藏  举报