# 用Python实现CSV数据处理程序


问题背景

本项目需要实现一个可读取并统计用户输入数据的简易程序,输入为包含性别、年龄和出生日期的CSV文件,输出结果包括统计信息和可视化图表。通过Python实现,可直接运行在本地环境,无需依赖外部框架。


问题分析

该程序需要完成以下核心功能:

  1. 读取CSV文件:使用Python的csv模块读取包含性别、年龄和出生日期的三列数据。
  2. 解析数据结构:将数据转换为列表或字典格式,便于后续统计。
  3. 统计信息
    • 总人数:统计所有行数,计算总人数。
    • 年龄分布:统计各年龄段的出现次数。
    • 生日分布:统计不同生日对应的年龄。
  4. 可视化图表:使用matplotlib生成柱状图或饼图展示统计结果。

代码实现

import csv

# 读取CSV文件
def read_csv_file(file_path):
    with open(file_path, 'r') as file:
        reader = csv.reader(file)
        data = []
        headers = next(reader, None)
        for row in reader:
            data.append(row)
        return data, headers

# 统计信息
def calculate_statistics(data, headers):
    total_people = len(data)
    age_distribution = {}
    birthday_distribution = {}

    # 统计年龄分布
    for row in data:
        age = int(row[1])
        if age in age_distribution:
            age_distribution[age] += 1
        else:
            age_distribution[age] = 1

    # 统计生日分布
    for row in data:
        if row[2] in birthday_distribution:
            birthday_distribution[row[2]] = 1
        else:
            birthday_distribution[row[2]] = 1

    return total_people, age_distribution, birthday_distribution

# 生成可视化图表
def plot_statistics(results):
    plt.figure(figsize=(10, 6))

    # 统计信息
    stats = results

    # 绘制柱状图
    plt.subplot(1, 2, 1)
    for stats_key, stats_value in stats.items():
        plt.barh([stats_key], stats_value)
        plt.title(f'统计信息: {stats_key} ({stats_value})')

    # 绘制饼图
    plt.subplot(1, 2, 2)
    for key in stats:
        pie_data = [stats[key] / stats[0] for key in stats]
        plt.pie(pie_data, labels=[f'{v:.2f}%' for v in pie_data])
        plt.title(f'统计结果: {key}')

    plt.show()

# 示例运行
if __name__ == "__main__":
    file_path = "data.csv"
    data, headers = read_csv_file(file_path)
    stats_info, age_distr, birthday_distr = calculate_statistics(data, headers)

    # 生成可视化图表
    plot_statistics((stats_info, age_distr, birthday_distr))

代码注释

  1. 读取CSV文件:使用csv.reader逐行读取数据,并保存为列表或字典。
  2. 统计信息
    • total_people:统计所有行的数目。
    • age_distribution:统计各年龄段的出现次数。
    • birthday_distribution:统计不同生日的出现次数。
  3. 可视化图表
    • 使用matplotlib生成柱状图和饼图,直观展示统计信息。
  4. 输出结果:通过plot_statistics函数展示统计结果,并保存图表。

总结

本项目通过Python实现CSV数据处理功能,使用了csv模块读取数据,并通过matplotlib生成可视化图表。项目实现了数据统计、信息展示和可视化需求,可在本地环境运行,无需依赖外部服务。