编码练习5

习题1:把一个文件中的所有数字都去掉。
在这里插入图片描述

filtered_content=""
with open("f:\\a.txt","r",encoding="utf-8") as fp:
    content = fp.read()
    for i in content:
        if i >="0" and i <="9":
            continue
        else:
            filtered_content+=i

with open("f:\\a.txt","w",encoding="utf-8") as fp:
    fp.write(filtered_content)

with open("f:\\a.txt","r",encoding="utf-8") as fp:
    print(fp.read())

在这里插入图片描述
习题2:
多级目录的多个文件中,要把所有字母去掉。

import os.path
file_path = []
for root,dirs,files in os.walk("f:\\letter"):
    for file in files:
        file_path.append(os.path.join(root,file))

print(file_path)

for file in file_path:
    filter_content = ""
    with open(file) as fp:
        content = fp.read()
        for letter in content:
            if (letter >="a" and letter<="z") \
                or (letter >="A" and letter<="Z"):
                continue
            else:
                filter_content+=letter

    with open(file,"w") as fp:
        fp.write(filter_content)

在这里插入图片描述
习题3:
写一个python小程序,输入是年月日,计算距离1949-10-1的天数。

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


def count_days_interval():
    input_date = input("请输入日期,格式:year-month-day:")
    if input_date.count("-")!=2:
        print("输入日期格式有误,格式year-month-day,请重新输入日期:")
        return None
    year,month,day = input_date.split("-")
    if not (year.isdigit() and month.isdigit() and day.isdigit()):
        print("输入日期格式有误,格式year-month-day,请重新输入日期:")
    year = int(year)
    month = int(month)
    day = int(day)
    
    init_year = 1949
    init_month = 10
    init_day = 1

    if year - init_year ==0:
        if month == init_month:
            return day - init_day
        elif month - init_month ==1:
            return 31+day-1
        else:
            return 31+30+day-1
    elif year - init_year ==1:
        month_days = [31,28,31,30,31,30,31,31,30,31,30,31]
        leap_day = 0
        if month >2 and is_leap_year(year):
            leap_day = 1
        days = 0
        for i in month_days[:month-1]:
            days+=i
        return 92+leap_day+days+day
    else:
        month_days = [31,28,31,30,31,30,31,31,30,31,30,31]
        leap_day = 0
        if month >2 and is_leap_year(year):
            leap_day = 1
        days = 0
        for i in month_days[:month-1]:
            days+=i
        leap_days=0
        for i in range(1950,year):
            if is_leap_year(i):
                leap_days+=1
        years = year - init_year -1
        return 92+leap_day+days+day+years*365+leap_days

print(count_days_interval())

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值