如何使用Python的`collections`模块中的`defaultdict`来统计一段文本中每个单词的出现次数?

在 Python 中,collections 模块提供了 defaultdict 类,它是一种特殊的字典,可以自动为不存在的键提供一个默认值。defaultdict 非常适合用来统计一段文本中每个单词的出现次数,因为它可以避免在每次遇到新单词时手动检查键是否存在的问题。

defaultdict 的基本用法

defaultdict 的构造函数接受一个可调用对象(如 int、list 等)作为参数,用于为不存在的键提供默认值。在统计单词出现次数时,我们可以将默认值设为 0,这样每次遇到新单词时,其初始计数会自动初始化为 0。

示例代码

以下是一个完整的示例,展示如何使用 defaultdict 统计文本中每个单词的出现次数:

from collections import defaultdict

def count_words(text):
    # 初始化一个 defaultdict,默认值为 0
    word_count = defaultdict(int)
    
    # 将文本按空格分割成单词列表
    words = text.split()
    
    # 遍历每个单词,更新计数
    for word in words:
        word_count[word] += 1
    
    return word_count

# 示例文本
text = "apple banana apple orange banana apple"
result = count_words(text)
print(result)

运行结果

运行上述代码后,输出如下:

defaultdict(<class 'int'>, {'apple': 3, 'banana': 2, 'orange': 1})

可以看到,defaultdict 正确地统计了每个单词的出现次数:apple 出现 3 次,banana 出现 2 次,orange 出现 1 次。

详细说明

  1. 初始化 defaultdict:

    word_count = defaultdict(int)
    

    这里 int 是一个可调用对象,返回默认值 0。如果字典中没有某个键,访问时会自动调用 int(),生成 0 作为默认值。

  2. 分割文本:

    words = text.split()
    

    split() 方法默认按空格分割文本,生成一个单词列表。

  3. 更新计数:

    for word in words:
        word_count[word] += 1
    

    每次遇到一个单词,直接对其值加 1。如果单词不存在,defaultdict 会自动初始化为 0,然后加 1。

对比普通字典

如果使用普通字典,我们需要手动检查键是否存在:

word_count = {}
for word in words:
    if word not in word_count:
        word_count[word] = 0
    word_count[word] += 1

defaultdict 简化了这一过程,代码更简洁易读。

其他应用

defaultdict 不仅适用于计数,还可以用于其他场景,比如分类:

from collections import defaultdict

animals = ["cat", "dog", "bird", "cat", "dog"]
animal_groups = defaultdict(list)

for animal in animals:
    animal_groups[animal].append(animal)

print(animal_groups)

输出:

defaultdict(<class 'list'>, {'cat': ['cat', 'cat'], 'dog': ['dog', 'dog'], 'bird': ['bird']})

总结

使用 defaultdict 可以高效地解决统计问题,避免了冗余的键检查代码。它的主要优势在于:

  1. 简洁性:无需手动初始化键值。
  2. 可读性:代码意图更清晰。
  3. 灵活性:支持多种默认值类型(如 int、list、set 等)。

如果你需要处理类似的数据统计任务,defaultdict 是一个非常实用的工具。