中国有句俗语叫“三天打鱼两天晒网”。某人从2010年1月1日起开始“三天打鱼两天晒网”,问这个人在以后的某一天中是“打鱼”还是“晒网”。

import re
import datetime
import sys

#确定文件名
filename='in.txt'
recordname='out.txt'
#读取用户查询日期
checkDate=input("请输入要查询的日期...\n")

#正则表达式验证用户输入数据正确性算法  如果输入不正确则停止程序运行
rex="([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8])))|(([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))0229"
if(re.search(rex,checkDate)):
    print("输入日期正确,已将结果存入out.txt...")
else:
    print("输入日期错误,不存在这一天或输入格式不对")
    sys.exit(0)

#打开文件并且存储用户查询日期
with open(filename,'a') as file_object:
    file_object.write(' '+checkDate)

#求日期差算法
def days(str1,str2):
    date1=datetime.datetime.strptime(str1[0:10],"%Y-%m-%d")
    date2=datetime.datetime.strptime(str2[0:10],"%Y-%m-%d")
    num=(date1-date2).days
    return num

#判断打鱼还是晒网算法
def check(num):
    num=num%5
    if num in range(1,4,1):
        return True
    else:
        return False

#核心算法
with open(filename) as file_object:
    contents=file_object.read()
    s1 = re.split(' ', contents)  # 利用正则函数进行分割
    #读取第一个数20100101和最后一个要查的数并将其转换为date数据类型
    begin=s1[0]
    begin=begin[0:4]+'-'+begin[5:6]+'-'+begin[7:8]
    last=s1[len(s1)-1]
    last=last[0:4]+'-'+last[5:6]+'-'+last[7:8]
    #调用days函数求出两日期之间所差天数
    nums=days(last,begin)
    #根据所差天数得到结果
    Result=check(nums)

#将结果写入out.txt文件中,其中True表示打鱼,False表示晒网
with open(recordname,'a') as file_object:
    file_object.write(str(Result)+' ')

猜你喜欢

转载自blog.csdn.net/qq_39621439/article/details/82184764