# 文件单词统计脚本实现与示例


背景介绍

本脚本旨在实现对本地目录中所有.txt文件内容中单词的统计功能。通过Python标准库的collectionsopen读取文件,结合数据处理思想,实现了文件内容的统计任务。该脚本不仅解决了文件内容处理的核心问题,还为读者展示了基础的字符串处理方法与统计逻辑。

思路分析

该问题具备以下特点:
1. 文件遍历与统计:脚本通过遍历目录中的.txt文件,统计每个单词出现的次数。
2. 数据处理与统计:使用字典统计单词的出现频率,避免重复计数。
3. 独立运行:无需依赖第三方库,可直接运行。

代码实现

import os
from collections import defaultdict

def count_words_in_txt_files(directory_path):
    words_freq = defaultdict(int)
    files = os.listdir(directory_path)

    for file in files:
        if file.endswith('.txt'):
            with open(os.path.join(directory_path, file), 'r') as f:
                content = f.read()
                words = content.split()
                for word in words:
                    words_freq[word] += 1

    return words_freq

# 示例使用
if __name__ == "__main__":
    result = count_words_in_txt_files("current_directory")
    print(result)

示例结果

输入文件内容:hello world this is a test

输出结果:{'hello': 1, 'world': 1, 'this': 1, 'is': 1, 'a': 1, 'test': 1}

总结

该脚本通过模块化设计实现了文件内容的单词统计功能,展示了基础的字符串处理和数据统计能力。该实现不仅解决了问题,还为后续学习字符串处理和数据统计提供了基础经验。该脚本可运行,无需依赖外部框架或服务,并且在1~3天内可实现,具备良好的可扩展性和实用性。