【作业】2022.5.7 csv文件操作

作业1:将酒店数据按照地区分类放入地区对应csv文件中

import csv

class CSVClassify:
    """
    这是一个对CSV文件按关键词整理的类
    """

    def __init__(self, path):
        self.path = path

    def get_origin_data(self):
        """
        获取CSV文件中数据的函数
        :return: 获取到的数据(列表形式)
        """
        return csv.reader(open(self.path, encoding='utf-8', newline=''))

    def get_head(self):
        """
        获取表头的函数
        :return: 表头
        """
        global origin_data
        origin_data = self.get_origin_data()
        return next(origin_data)

    def generate_new_csv(self, keywords):
        """
        生成以关键词命名的CSV文件的函数
        :param keywords: 关键词列表
        :return: 无
        """
        for keyword in keywords:
            csv.writer(open(f'{keyword}.csv', 'w', encoding='utf-8')).writerow(self.get_head())

    def classify(self, keywords, position=1):
        """
        正式进行分类操作的函数
        :param position: 关键词位于CSV文件的列数(从0开始数)
        :param keywords: 关键词列表
        :return: 无
        """
        self.generate_new_csv(keywords)
        for x in origin_data:
            if x[position] in keywords:
                csv.writer(open(f'{x[position]}.csv', 'a', encoding='utf-8')).writerow(x)


if __name__ == '__main__':
    hotel_data = CSVClassify('北京高档酒店价格分析.csv')
    hotel_data.classify(keywords=['海淀区', '东城区', '朝阳区', '其他城区'])

作业2:基于落户积分文件:

(1)计算所有人平均年龄

(2)修改每个人的生日,随机添加日(考虑平年闰年和大小月)

(3)将所有狮子座的人对应的数据放入一个单独的csv文件中

from datetime import datetime

class Constellation:
    def __init__(self, path):
        self.path = path

    def get_datetime(self, birthday):
        try:
            datetime0 = datetime.strptime(birthday, '%Y-%m')
        except:
            datetime0 = datetime.strptime(birthday[:7], '%Y-%m')

        return datetime0

    def is_leap_year(self, year):
        if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
            return True
        else:
            return False

    def generate_day(self, birthday_datetime):
        from random import randint

        if birthday_datetime.month in [1, 3, 5, 7, 8, 10, 12]:
            return randint(0, 30)

        elif birthday_datetime.month in [4, 6, 9, 11]:
            return randint(0, 29)

        else:
            year = birthday_datetime.year
            if self.is_leap_year(year):
                return randint(0, 28)
            else:
                return randint(0, 27)

    def complete_birthday(self, birthday_datetime):
        from datetime import timedelta
        return birthday_datetime + timedelta(self.generate_day(birthday_datetime))

    def age(self, full_birthday):
        time_now = datetime.now()
        age_0 = time_now.year - full_birthday.year
        if time_now.month > full_birthday.month:
            return age_0
        elif time_now.month < full_birthday.month:
            return age_0 - 1
        else:
            if time_now.day >= full_birthday.day:
                return age_0
            else:
                return age_0 - 1

    def decide_const(self, full_birthday):
        month1 = full_birthday.month
        day1 = full_birthday.day

        # 只判断狮子座,其他的星座不管了
        if (month1 == 7 and day1 >= 23) or (month1 == 8 and day1 <= 22):
            return 'leo'


# 作业第1题专用函数
def csv_avg(path, position=2):
    count_person = 0
    sum_age = 0

    csv_1 = Constellation(path)
    origin_data = csv.reader(open(path, 'r', encoding='utf-8', newline=''))
    next(origin_data)

    for x in origin_data:
        birthday_0 = csv_1.get_datetime(x[position])
        birthday_1 = csv_1.complete_birthday(birthday_0)
        age = csv_1.age(birthday_1)
        count_person += 1
        sum_age += age

    return f"{sum_age / count_person:.2f}"


# 作业第2题专用函数
def add_day(path, position=2):
    csv_1 = Constellation(path)
    origin_data = csv.reader(open(path, 'r', encoding='utf-8', newline=''))
    new_data = [next(origin_data)]

    for x in origin_data:
        birthday_0 = csv_1.get_datetime(x[position])
        birthday_1 = csv_1.complete_birthday(birthday_0)
        x[position] = birthday_1.strftime('%Y-%m-%d')
        new_data.append(x)

    csv.writer(open(path, 'w', encoding='utf-8', newline='')).writerows(new_data)


# 作业第三题专用函数
def constellation_classify(path, position=2, target_constellation='leo'):
    csv_1 = Constellation(path)
    origin_data = csv.reader(open(path, 'r', encoding='utf-8', newline=''))
    new_data = [next(origin_data)]

    for x in origin_data:
        birthday_1 = datetime.strptime(x[position], '%Y-%m-%d')
        constellation = csv_1.decide_const(birthday_1)

        if constellation == target_constellation:
            new_data.append(x)

    csv.writer(open(f'{target_constellation}.csv', 'w', encoding='utf-8')).writerows(new_data)


if __name__ == '__main__':
    # 作业第1题
    print(csv_avg('2018年北京积分落户数据.csv'))

    # 作业第2题
    add_day('2018年北京积分落户数据.csv')

    # 作业第3题
    constellation_classify('2018年北京积分落户数据.csv')
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sprite.Nym

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值