第十次作业

练习题:
1、 假设你获取了用户输入的日期和时间如2020-1-21 9:01:30,以及一个时区信息如UTC+5:00,均是str,请编写一个函数将其转换为timestamp:
import re
from datetime import datetime, timezone, timedelta

def to_timestamp(dt_str, tz_str):
input_dt = datetime.strptime(dt_str, ‘%Y-%m-%d %H:%M:%S’)

time_zone_num = re.match(r'UTC([+|-][\d]{1,2}):00', tz_str).group(1)
time_zone = timezone(timedelta(hours=int(time_zone_num)))  # 创建时区UTC-??

input_dt_tz = input_dt.replace(tzinfo=time_zone)

return input_dt_tz.timestamp()

t1 = to_timestamp(‘2020-1-21 9:01:30’, ‘UTC+5:00’)
1、 assert t1 == 1433121030.0, t1
2、编写Python程序以选择指定年份的所有星期日。

import calendar
import datetime
import csv

def getAllDayList(year):
cal = calendar.Calendar()
alldaylist = []
for month in list(range(1,13)):
listday = []
for day in cal.itermonthdays(year,month):
if day != 0:
listday.append(day)
alldaylist.append(listday)
return alldaylist

def getdaydate(year,alldaylist,zj):
‘’‘获取指定周几的所有日期’’’
filterdate = []
for month in list(range(1,13)):
for day in alldaylist[month - 1]:
date = datetime.date(year,month,day)
#调用datetime类的isoweekday()方法,过滤出指定周几的日期
if date.isoweekday() == zj:
tmpstr = str(date.year) + “,” + str(date.month) + “,” + str(date.day)
filterdate.append(tmpstr)
return filterdate

def writeintocsv(filterdate):
tmp = []
with open(“HuoQuRiQi.csv”,‘w’,newline=’’) as f:
opw = csv.writer(f,delimiter=",")
for i in filterdate:
tmp = i.split(’,’)
opw.writerow(tmp)

def writeintotxt(filterdate):
with open(“HuoQuRiQi.txt”,‘w’) as f:
for i in filterdate:
f.write(i+"\n")

if name == ‘main’:
year = int(input(“年份(四位数字):”))
day = 7
zjdate = getdaydate(year,getAllDayList(year),day)
writeintocsv(zjdate)
writeintotxt(zjdate)

练习题:
1、打开中文字符的文档时,会出现乱码,Python自带的打开文件是否可以指定文字编码?还是只能用相关函数?
首先需要了解目前的编码方式是什么,然后再用decode或者encode去编码和解码,下面是使用chardet库来查看编码方式的。
2、编写程序查找最长的单词
输入文档: res/test.txt
题目说明:
import re

def longest_word(filename):
f = open(filename, mode=‘r’)
lst1 = f.readlines()
lst2 = []
lst3 = []
for i in range(len(lst1)):
str1 = lst1[i]
lst2 = lst2 + re.split(’ |,|\n’, str1)
temp = len(lst2[0])
lst3.append(lst2[0])
ind = 0
for j in range(len(lst2)-1):
if len(lst2[j+1]) > temp:
lst3 = []
temp = len(lst2[j+1])
lst3.append(lst2[j+1])
ind = j+1
if len(lst2[j+1]) == temp:
lst3.append(lst2[j+1])
return lst3

print(longest_word(“t.txt”))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值