# 小项目:文本文件频率统计与数据持久化


背景介绍

本项目旨在实现对用户输入文本文件的统计功能,包括频率统计和结果保存。通过读取文件内容,统计关键词出现频率,最终将结果保存到本地文件中。项目依赖本地文件操作,可扩展为CSV文件处理或实时统计,同时学习文件读写与数据结构的应用。

思路分析

核心功能

  1. 文件读取:使用Python的open()函数读取本地文件
  2. 频率统计:使用字典记录单词出现次数
  3. 结果保存:将统计结果以文本形式写入本地文件

数据结构

  • 使用字典word_counts存储统计结果,简化频率计算
  • 通过字符串拆分将输入文本转换为单词列表

代码实现

# 本代码实现文本文件频率统计并保存结果  

# 读取本地文件  
def read_text_file(file_path):
    with open(file_path, 'r') as f:
        content = f.read().strip()
    return content

# 统计频率  
def count_words(text):
    word_counts = {}
    words = text.split()
    for word in words:
        word_counts[word] = word_counts.get(word, 0) + 1
    return word_counts

# 保存结果到本地文件  
def write_result_to_file(result, file_path):
    with open(file_path, 'w') as f:
        f.write(f"统计结果:{result}\n")

# 示例使用  
if __name__ == "__main__":
    input_text = "apple orange banana"
    word_counts = count_words(input_text)
    result = str(word_counts)
    file_path = "frequency_results.txt"
    print("输入文本内容:", input_text)
    print("统计结果:", word_counts)
    write_result_to_file(result, file_path)

总结

本项目实现了文本文件的频率统计功能,通过文件读写操作实现数据处理,并将结果保存到本地文件中。代码清晰、注释明确,能够支持扩展为CSV文件处理或实时统计功能。学习价值在于理解文件处理的核心逻辑,以及数据结构的应用。