Python学习--Day 24

175.datetime

  • datetime模块,可以理解为是time模块的升级版,包含time(时间)、date(日期)、datetime(日期时间)、timedelta(时间差)。需要引入import datetime
    一部分具体用法参看下面代码
import datetime
import time
# 得到hour对象
print(datetime.time.hour) # <attribute 'hour' of 'datetime.time' objects>
# 得到当前的小时数:
print(time.localtime().tm_hour) # 19
# 得到day对象
print(datetime.date.day) # <attribute 'day' of 'datetime.date' objects>
# 创建一个date对象
d = datetime.date(2019,6,20)
# 转化时间戳为字符串
print(datetime.date.ctime(d)) # Thu Jun 20 00:00:00 2019
# 获得date对象中的day
print(d.day) # 20
# 今天的日期
print(datetime.date.today()) # 2020-08-13
  • datetime.timedelta日期时间对象的差值,主要负责两个不同日期之间的处理。主要内容:detetime.timedelta()方法内设置一些参数,方便进行date.timedelta()计算时间差值;记忆datetime.datetime.now()是获取当前时间。
import datetime
now = datetime.datetime.now() #datetime模块下的datetime模块有now方法
print(now)
timedel = datetime.timedelta(hours=2) # 可以传输weeks = 3等,进行三周前的数据操作等
result = now - timedel
print(result)
# 2020-08-13 19:42:10.893897
# 2020-08-13 17:42:10.893897

176.作业

  • 作业是继承的作业,应该属于老师讲课内容的day17,属于我的笔记中day22。
  • 主要还是多继承的顺序,从左至右广度优先。

177.random

  • random.randrange(a,b,step)从a-b范围内以步长step随机选择整数输出,但不包括b。

  • random.randint(a,b)从a-b范围内选择整数,包括b。

  • random.choice(seq)从序列seq中随机选择一个对象(比如列表随机抽取)

  • random.shuffle(seq)将序列seq中的内容随机打乱(比如数组的随机打乱)

  • 示例:验证码随机产生:使用了random.choice(),属于用新方法解决问题。

import random
def func():
    code = ''
    for i in range(4):
        ran1 = str(random.randint(0,9))
        ran2 = chr(random.randint(65,90))
        ran3 = chr(random.randint(97,122))
        x = random.choice([ran1,ran2,ran3])
        code += x
    return code
c = func()
print(c)

178.hashlib

  • chr、ord
    chr:将Unicode码转成str
    str:将str转成Unicode码
print(ord('上')) # 19978
print(chr(12948)) # ㊔
  • hash模块,decode和incode,需要引入import hashlib
    hashlib.md5(待加密对象.encode('utf-8')),不能直接给md5方法传输字符串格式对象,要先encode为utf-8格式的数据;查看该加密后的对象要调用函数:md5加密对象.hexdigest(),其中hex代表以16进制输出。
  • 加密算法中,md5、sha1、sha256是单向加密,针对算法底层人员是可以解开的;base是双向加密算法,可以解开。
  • 示例:
import hashlib
d = 'Amy'
md5 = hashlib.md5(d.encode('utf-8'))
print(md5.hexdigest()) # 705da23959fa17c5d11d7a53a6157a19
sha1 = hashlib.sha1(d.encode()) #默认utf-8
print(sha1.hexdigest()) # 61bf74cd011587a9421377c6c34199bf41a0339d
sha256 = hashlib.sha256(d.encode())
print(sha256.hexdigest()) # 6410ef0d3a6d3324fcba02131e5742215c99301055398a75457a27ac89dffb5f
  • 在实际的开发过程中,经常使用hashlib调用加密算法对用户的密码等进行加密,使用加密后的数据与数据库进行比对。

179.第三方的简单使用

  • 在pychram中使用第三方的代码包:方法1:打开终端,使用pip安装对应的模块;方法2,打开设置,在project interpreter中pychram提供的模块库中寻找(我的这个不好用,不细说了);方法3:
    方法1

180.正则简介(match和search)

  • 正则表达式(简称RE)的定义:正则表达式是对字符串操作的一种逻辑公式,就是用事先定义好的一些特定字符,及这些特定字符的组合,组成一个‘规则字符串’,这个‘规则字符串’用来表达对字符串的一种过滤逻辑。
  • 正规表达式的作用:给定一个正则表达式和另一个字符串,我们可以达到如下的目的:①.给定的字符产是否符合正则表达式的过滤逻辑(称作匹配);②.可以通过正则表达式,从字符串中获取我们想要的特定部分。
  • 正则表达式的特点:灵活、有逻辑性、功能性强、迅速达到字符串的复杂控制。
  • python中使用正则表达式,要引入re模块:import re
  • 正则re模块的match()只从头开始匹配,如果匹配成功会返回一个对象,没有匹配返回None。
import re
msg = '佟丽娅热巴'
msg2 = '热巴佟丽娅'
pattern = re.compile('佟丽娅')
s = pattern.match(msg) # match是从头匹配,在这里没有匹配,是None
print(s) # <_sre.SRE_Match object; span=(0, 3), match='佟丽娅'>
s2 = pattern.match(msg2)
print(s2) # None
  • 正则re模块的search(),不只是从头匹配,而是逐个查找。
    search返回的结果.span()可以返回具体的位置。
    search返回的结果.group()可以返回匹配的数据,提取匹配到的数据。
import re
msg = '佟丽娅热巴'
msg2 = '热巴佟丽娅'
pattern = re.compile('佟丽娅')
s = pattern.search(msg)
print(s) # <_sre.SRE_Match object; span=(0, 3), match='佟丽娅'>
s2 = pattern.search(msg2)
print(s2) # <_sre.SRE_Match object; span=(2, 5), match='佟丽娅'>
print(s2.span()) # (2, 5)
print(s2.group()) # 佟丽娅

181.正则表达式次数

  • 正则表达式的符号:
    可以自行查看python源码:re模块,下面是从源码搬运过来的。
'''
The special characters are:
    "."      Matches any character except a newline.
    "^"      Matches the start of the string.
    "$"      Matches the end of the string or just before the newline at 
             the end of the string.
    "*"      Matches 0 or more (greedy) repetitions of the preceding RE.
             Greedy means that it will match as many repetitions as possible.
    "+"      Matches 1 or more (greedy) repetitions of the preceding RE.
    "?"      Matches 0 or 1 (greedy) of the preceding RE.
    *?,+?,?? Non-greedy versions of the previous three special characters.
    {m,n}    Matches from m to n repetitions of the preceding RE.
    {m,n}?   Non-greedy version of the above.
    "\\"     Either escapes special characters or signals a special sequence.
    []       Indicates a set of characters.
             A "^" as the first character indicates a complementing set.
    "|"      A|B, creates an RE that will match either A or B.
    (...)    Matches the RE inside the parentheses.
             The contents can be retrieved or matched later in the string.
    (?aiLmsux) Set the A, I, L, M, S, U, or X flag for the RE (see below).
    (?:...)  Non-grouping version of regular parentheses.
    (?P<name>...) The substring matched by the group is accessible by name.
    (?P=name)     Matches the text matched earlier by the group named name.
    (?#...)  A comment; ignored.
    (?=...)  Matches if ... matches next, but doesn't consume the string.
    (?!...)  Matches if ... doesn't match next.
    (?<=...) Matches if preceded by ... (must be fixed length).
    (?<!...) Matches if not preceded by ... (must be fixed length).
    (?(id/name)yes|no) Matches yes pattern if the group with id/name matched,
                       the (optional) no pattern otherwise.
'''
  • 提取前后是字母、中间是数字的格式数据:
    search('正则表达式', seq),正则表达式使用[]内写上条件,[0-9]表示该处是数字,[a-z]表示该处是小写字母,以此类推。在此基础上使用group()进行查看匹配内容。且search的特点是(懒),只返回第一个匹配的对象,不会继续查找。
import re
msg = 'gsauat56t6ykjd3c'
result = re.search('[a-z][0-9][a-z]',msg) # 搜索中间是数字,两边是字母的字符串
print(result) # <_sre.SRE_Match object; span=(8, 11), match='t6y'>
print(result.group()) # t6y
  • 使用findall()将所有符合特点的内容都返回:匹配整个字符串。
import re
msg = 'gsauat56t6ykjd3c'
result = re.findall('[a-z][0-9][a-z]',msg) # 搜索中间是数字,两边是字母的字符串
print(result) # ['t6y', 'd3c']
  • 新需求:两头是字母,中间是随便多少数字都可以:a7a、a567a、a78b、h786j、h9845k
    *表示选定的模式出现次数大于等于0;+表示选定的模式出现次数至少有一次;?表示将前面的模式匹配0次或者1次,都是贪婪模式,尽可能多地匹配。将对应的符号放到表达式的后面
import re
msg = 'a7afra567ayua78bh786jh9845k'
result = re.findall('[a-z][0-9]+[a-z]',msg) # 搜索中间是数字,两边是字母的字符串
print(result) # ['a7a', 'a567a', 'a78b', 'h786j', 'h9845k']
  • '{m,n}'用于将前面的模式匹配m次到n次,即最小匹配m次,最大匹配n次。示例:
import re
msg = '9812741'
result = re.match('[1-9][0-9]{4,10}',msg) 
print(result) # <_sre.SRE_Match object; span=(0, 7), match='9812741'>
  • 行首符号:^,行尾符号:$,行首符号,表示将正则表达式作为一个整体进行匹配,而不是从字符串中逐个搜索。要加在正则表达式上。参见下面的代码示例,不加符号与加符号的区别。
import re
msg = '9812741'
result = re.match('^[1-9][0-9]{4}$',msg) # 使用行首行尾符号进行限制,匹配至末尾。
print(result) # None
result = re.match('[1-9][0-9]{4}',msg) #不适用行首行尾符号进行限制,匹配至开头。
print(result) # <_sre.SRE_Match object; span=(0, 5), match='98127'>
  • 实战,验证qq号码5-11位且首位不为0:
import re
msg = '9812741'
result = re.match('^[1-9][0-9]{4}$',msg) # 使用行首行尾符号进行限制,匹配至末尾。

正则表达式是针对字符串进行的。

  • 对应的,*?+???{m,n}?*+?{m,n}的非贪婪模式,也就是尽可能少的匹配。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值