Python 用Counter做映射

  • Post category:Python

Python 的 Counter 类是一个集合类型,用于计算可哈希对象的个数。它是 dict 的子类,可以用于计数相同元素出现的次数。在处理文本、数据分析、自然语言处理等方面都有广泛的应用。

使用 Counter 需要导入它,可以在代码的开头添加以下 import 语句:

from collections import Counter

创建 Counter 对象

创建 Counter 对象可以使用以下方式:

c = Counter() # 创建空的 Counter
c = Counter('hello') # 计算字符串 'hello' 中每个字符的出现次数
c = Counter({'red': 4, 'blue': 2}) # 使用字典创建 Counter
c = Counter(cats=4, dogs=7) # 使用关键字参数创建 Counter

计数器操作

使用 Counterupdate() 方法可以增加计数器的值。参数可以是列表、元组、字典和 Counter 对象等。

c = Counter(a=3, b=1)
c.update(['a', 'b', 'b', 'c']) # 从列表中更新计数器
print(c) # Counter({'a': 4, 'b': 3, 'c': 1})
c.update({'a': 2, 'c': 1}) # 从字典中更新计数器
print(c) # Counter({'a': 6, 'b': 3, 'c': 2})

使用 Countermost_common() 方法可以根据计数器的值对元素进行排序,并返回前 n 个元素和它们的计数值。

c = Counter(a=3, b=1, c=2)
print(c.most_common()) # [('a', 3), ('c', 2), ('b', 1)]
print(c.most_common(2)) # [('a', 3), ('c', 2)]

示例说明

示例一:统计单词出现次数

下面是一个示例程序,可以统计文本文件中每个单词出现的次数,并按照出现次数进行降序排列:

from collections import Counter

def count_words(file_path):
    # 读取文本文件
    with open(file_path, 'r') as f:
        text = f.read().lower()
    # 按照空格分割字符串,统计每个单词的出现次数
    word_count = Counter(text.split())
    # 按照出现次数降序排列
    sorted_word_count = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
    return sorted_word_count

print(count_words('example.txt'))

上述代码读取文本文件 example.txt,统计其中每个单词的出现次数,并将结果按照出现次数进行降序排列。

示例二:统计字符串中的字母出现次数

下面是一个示例程序,可以统计字符串中每个字母出现的次数,并打印结果:

from collections import Counter

def count_letters(text):
    # 按照字符分割字符串,统计每个字母的出现次数
    letter_count = Counter(text)
    # 打印结果
    for letter, count in letter_count.items():
        print('{}: {}'.format(letter, count))

count_letters('hello, world!')

上述代码统计字符串 hello, world! 中每个字母出现的次数,并打印结果。