• 统计字符出现次数类Counter


    统计字符出现次数类Counter

    1.概述

    当我们的业务中需要做统计工作时可以先考虑下python标准库中collections模块提供的Counter类,该类可以对可哈希对象次数进行统计。

    2.Counter类

    2.1.Counter类介绍

    • collections在python官方文档中的解释是High-performance container datatypes,直接的中文翻译解释高性能容量数据类型,该模块下主要包含了如下的类:

      • _OrderedDictKeysView
      • _OrderedDictItemsView
      • _OrderedDictValuesView
      • _Link
      • OrderedDict
      • Counter
      • ChainMap
      • UserDict
      • UserList
      • UserString
    • Counter类是dict的子类,它只能用于计算可散列(可哈希)对象的次数。

    • 什么是可散列对象那,就是集合中的可哈希对象,通过调用hash(被测试对象)返回值为true则该对象就是可哈希对象,哪些是可哈希对象那?

      • 所有不可变内置类型,都是可哈希的,比如str、int 、tuple 、frozenset
      • 所有可变内置类型,都是不可哈希的,比如dict、list 、set
      • 对于不可变容器类型,仅当他所有成员都不可变时,他自身才是可哈希的。
      • 用户定义的类型默认都是可哈希的。

    2.2.Counter类统计示例

    统计一个列表中每个单词出现的次数,下面使用常规的方式实现了功能。

    #统计词频
    colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
    result = {}
    for color in colors:
        if result.get(color)==None:
            result[color]=1
        else:
            result[color]+=1
    print (result)
    #{'red': 2, 'blue': 3, 'green': 1}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    如果使用Counter类来统计单词出现次数会变得更简单。

    from collections import Counter
    colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
    c = Counter(colors)
    print (dict(c))
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.3.Counter类方法

    1.创建Counter对象
    # 创建无参Counter对象
    cnt = Counter()
    
    # 传进字符串
    c1 = Counter('gallahad')
    print(c1)
    # 传进字典
    c2 = Counter({'red': 4, 'blue': 2})
    print(c2)
    # 传进元组
    c3 = Counter(cats=4, dogs=8)
    print(c3)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    2.查询元素
    # 查询的元素不存在返回0
    print(c2['black'])
    
    # 查询所有元素:elements(),返回一个迭代器,每个元素重复的次数为它的数目,顺序是任意的顺序,如果一个元素的数目少于1,那么elements()就会忽略它
    c = Counter(a=4, b=2, c=0, d=-2)
    list(c.elements())
    #['a', 'a', 'a', 'a', 'b', 'b']
    
    # 查看最常见出现的n个元素,返回一个列表,包含counter中n个最大数目的元素
    Counter('abracadabra').most_common(3)
    #[('a', 5), ('r', 2), ('b', 2)]
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    3.更新元素
    c = Counter(a=3, b=1)
    d = Counter(a=1, b=2)
    c + d                       # 相加
    #Counter({'a': 4, 'b': 3})
    c - d                       # 相减,如果小于等于0,删去
    #Counter({'a': 2})
    c & d                       # 求最小
    #Counter({'a': 1, 'b': 1})
    c | d                       # 求最大
    #Counter({'a': 3, 'b': 2})
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    3.Counter统计日志

    from collections import Counter
    lines = open("./data/input.txt","r").read().splitlines()
    lines = [lines[i].split(" ") for i in range(len(lines))]
    words = []
    for line in lines:
        words.extend(line)
    result = Counter(words)
    print (result.most_common(10))
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    当需要统计的文件比较大,使用read()一次读不完的情况:

    from collections import Counter
    result = Counter()
    with open("./data/input.txt","r") as f:
        while True:
            lines = f.read(1024).splitlines()
            if lines==[]:
                break
            lines = [lines[i].split(" ") for i in range(len(lines))]
            words = []
            for line in lines:
                words.extend(line)
            tmp = Counter(words)
            result+=tmp
    
    print (result.most_common(10))
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
  • 相关阅读:
    6-4应用层-电子邮件
    python函数的定义和使用
    【自动驾驶】单目3D检测M3D-RPN解析与paddle复现
    Golang源码分析:golang/sync之singleflight
    人工智能学习(五)人工智能三巨头
    SQL查找每个城市购买金额排名第二的用户,列出其购买城市、姓名、购买金额(排序函数)
    MQ - 10 RocketMQ的架构设计与实现
    【C++ STL】-- deque与vector相比的优势与劣势
    软件设计模式系列之二十——备忘录模式
    阅读笔记——SSR-Net: A Compact Soft Stagewise Regression Network for Age Estimation
  • 原文地址:https://blog.csdn.net/m0_38039437/article/details/127658168