Python学习记录day6


title: Python学习记录day6
tags: python
author: Chinge Yang
date: 2016-12-03

Python学习记录day6

[TOC]python

1.反射

反射:利用字符串的形式去对象(默认)中操做(寻找)成员
cat commons.py正则表达式

#!/usr/bin/env python
#_*_coding:utf-8_*_
'''
 * Created on 2016/12/3 21:54.
 * @author: Chinge_Yang.
'''

def login():
    print("炫酷登陆")


def home():
    print("炫酷页面")


def logout():
    print("欢乐退出")

cat index.py算法

#!/usr/bin/env python
#_*_coding:utf-8_*_
'''
 * Created on 2016/12/3 21:56.
 * @author: Chinge_Yang.
'''


import commons

def run():
    if hasattr(commons, inp):
        inp = input("请输入要访问的url:")
        func = getattr(commons, inp)
        func()
    else:
        print("404")


if __name__ == "__main__":
    run()

以字符串方式导入模块:shell

obj = __import__("commons")
obj = __import__("commons.login", fromlist = True)

实例实质:伪造Web框架的路由系统
getattr,delattr,setattr,hasattr编程

2.经常使用模块

模块中的特殊变量:缓存

print(__doc__)	#获取文件开头的注释,(3个引号中间的信息) 

__cache__	#缓存pyc存放的位置

print(__file__)	#当前py文件所在的路径

os.path.abspath()	#获取文件的绝对路径
os.path.dirname()	#获取文件目录的名字
sys.path.append(os.path.dirname(os.path.abspath(__file__)))	#添加文件上层目录到python库

print(admin.__packages__)	#获取admin所在的包名
#只有执行当前文件时,当前文件的特殊变量__name__ == "__main__"

2.1 sys

用于提供对Python解释器相关的操做:bash

sys.argv           命令行参数List,第一个元素是程序自己路径
sys.exit(n)        退出程序,正常退出时exit(0)
sys.version        获取Python解释程序的版本信息
sys.maxint         最大的Int值
sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform       返回操做系统平台名称
sys.stdin          输入相关
sys.stdout         输出相关
sys.stderror       错误相关

进度条案例:app

#!/usr/bin/env python
# _*_coding:utf-8_*_
'''
 * Created on 2016/12/4 10:53.
 * @author: Chinge_Yang.
'''

import sys
import time


def view_bar(num, total):
    rate =  num / total
    rate_num = int(rate * 100)
    #r = '\r%d%%' % (rate_num, )
    r = '\r%s>%d%%' % (">" * num, rate_num)
    sys.stdout.write(r)
    sys.stdout.flush()


if __name__ == '__main__':
    for i in range(0, 100):
        time.sleep(0.1)
        view_bar(i, 100)

2.2 os

用于提供系统级别的操做:框架

os.getcwd()                 获取当前工做目录,即当前python脚本工做的目录路径
os.chdir("dirname")         改变当前脚本工做目录;至关于shell下cd
os.curdir                   返回当前目录: ('.')
os.pardir                   获取当前目录的父目录字符串名:('..')
os.makedirs('dir1/dir2')    可生成多层递归目录
os.removedirs('dirname1')   若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname')         生成单级目录;至关于shell中mkdir dirname
os.rmdir('dirname')         删除单级空目录,若目录不为空则没法删除,报错;至关于shell中rmdir dirname
os.listdir('dirname')       列出指定目录下的全部文件和子目录,包括隐藏文件,并以列表方式打印
os.remove()                 删除一个文件
os.rename("oldname","new")  重命名文件/目录
os.stat('path/filename')    获取文件/目录信息
os.sep                      操做系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep                  当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
os.pathsep                  用于分割文件路径的字符串
os.name                     字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command")   运行shell命令,直接显示
os.environ                  获取系统环境变量
os.path.abspath(path)       返回path规范化的绝对路径
os.path.split(path)         将path分割成目录和文件名二元组返回
os.path.dirname(path)       返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path)      返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path)        若是path存在,返回True;若是path不存在,返回False
os.path.isabs(path)         若是path是绝对路径,返回True
os.path.isfile(path)        若是path是一个存在的文件,返回True。不然返回False
os.path.isdir(path)         若是path是一个存在的目录,则返回True。不然返回False
os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径以前的参数将被忽略
os.path.getatime(path)      返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path)      返回path所指向的文件或者目录的最后修改时间

2.3 hashlib

用于加密相关的操做,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法编程语言

import hashlib
 
# ######## md5 ########
hash = hashlib.md5()
# help(hash.update)
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
print(hash.digest())
 
 
######## sha1 ########
 
hash = hashlib.sha1()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
 
# ######## sha256 ########
 
hash = hashlib.sha256()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
 
 
# ######## sha384 ########
 
hash = hashlib.sha384()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
 
# ######## sha512 ########
 
hash = hashlib.sha512()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
以上加密算法虽然依然很是厉害,但时候存在缺陷,即:经过撞库能够反解。因此,有必要对加密算法中添加自定义key再来作加密。

import hashlib
 
# ######## md5 ########
 
hash = hashlib.md5(bytes('ygqygq2',encoding="utf-8"))
hash.update(bytes('admin',encoding="utf-8"))
print(hash.hexdigest())
python内置还有一个 hmac 模块,它内部对咱们建立 key 和 内容 进行进一步的处理而后再加密

import hmac
 
h = hmac.new(bytes('ygqygq2',encoding="utf-8"))
h.update(bytes('admin',encoding="utf-8"))
print(h.hexdigest())

2.3 re

简介: 就其本质而言,正则表达式(或re)是一种小型的、高度专业化的编程语言,(在Python中)它内嵌在Python中,并经过re模块实现。正则表达式模式被编译成一系列的字节码,而后由用C编写的匹配引擎执行。

  • 字符: . 匹配除换行符之外的任意字符 \w 匹配字母或数字或下划线或汉字 \s 匹配任意的空白符 \d 匹配数字 \b 匹配单词的开始或结束 ^ 匹配字符串的开始 $ 匹配字符串的结束

  • 次数: * 重复零次或更屡次 + 重复一次或更屡次 ? 重复零次或一次 {n} 重复n次 {n,} 重复n次或更屡次 {n,m} 重复n到m次

Python提供re模块,包含全部正则表达式的功能。因为Python的字符串自己也用\转义,因此要特别注意:

s = 'ABC\\-001' # Python的字符串
# 对应的正则表达式字符串变成:
# 'ABC\-001'

所以咱们强烈建议使用Python的r前缀,就不用考虑转义的问题了:

s = r'ABC\-001' # Python的字符串
# 对应的正则表达式字符串不变:
# 'ABC\-001'

先看看如何判断正则表达式是否匹配:

>>> import re
>>> re.match(r'^\d{3}\-\d{3,8}$', '010-12345')
<_sre.SRE_Match object; span=(0, 9), match='010-12345'>
>>> re.match(r'^\d{3}\-\d{3,8}$', '010 12345')
>>>

分组
除了简单地判断是否匹配以外,正则表达式还有提取子串的强大功能。用()表示的就是要提取的分组(Group)。好比:

^(\d{3})-(\d{3,8})$分别定义了两个组,能够直接从匹配的字符串中提取出区号和本地号码:

>>> m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
>>> m
<_sre.SRE_Match object; span=(0, 9), match='010-12345'>
>>> m.group(0)
'010-12345'
>>> m.group(1)
'010'
>>> m.group(2)
'12345'

若是正则表达式中定义了组,就能够在Match对象上用group()方法提取出子串来。 注意到group(0)永远是原始字符串,group(1)、group(2)……表示第一、二、……个子串。 提取子串很是有用。来看一个更凶残的例子:

>>> t = '19:05:30'
>>> m = re.match(r'^(0[0-9]|1[0-9]|2[0-3]|[0-9])\:(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])\:(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])$', t)
>>> m.groups()
('19', '05', '30')

这个正则表达式能够直接识别合法的时间。可是有些时候,用正则表达式也没法作到彻底验证,好比识别日期: '^(0[1-9]|1[0-2]|[0-9])-(0[1-9]|1[0-9]|2[0-9]|3[0-1]|[0-9])$' 对于'2-30','4-31'这样的非法日期,用正则仍是识别不了,或者说写出来很是困难,这时就须要程序配合识别了。

编译
当咱们在Python中使用正则表达式时,re模块内部会干两件事情: 编译正则表达式,若是正则表达式的字符串自己不合法,会报错; 用编译后的正则表达式去匹配字符串。 若是一个正则表达式要重复使用几千次,出于效率的考虑,咱们能够预编译该正则表达式,接下来重复使用时就不须要编译这个步骤了,直接匹配:

>>> import re
# 编译:
>>> re_telephone = re.compile(r'^(\d{3})-(\d{3,8})$')
# 使用:
>>> re_telephone.match('010-12345').groups()
('010', '12345')
>>> re_telephone.match('010-8086').groups()
('010', '8086')

match

# match,从起始位置开始匹配,匹配成功返回一个对象,未匹配成功返回None
 
 
 match(pattern, string, flags=0)
 # pattern: 正则模型
 # string : 要匹配的字符串
 # falgs  : 匹配模式
     X  VERBOSE     Ignore whitespace and comments for nicer looking RE's.
     I  IGNORECASE  Perform case-insensitive matching.
     M  MULTILINE   "^" matches the beginning of lines (after a newline)
                    as well as the string.
                    "$" matches the end of lines (before a newline) as well
                    as the end of the string.
     S  DOTALL      "." matches any character at all, including the newline.
 
     A  ASCII       For string patterns, make \w, \W, \b, \B, \d, \D
                    match the corresponding ASCII character categories
                    (rather than the whole Unicode categories, which is the
                    default).
                    For bytes patterns, this flag is the only available
                    behaviour and needn't be specified.
      
     L  LOCALE      Make \w, \W, \b, \B, dependent on the current locale.
     U  UNICODE     For compatibility only. Ignored for string patterns (it
                    is the default), and forbidden for bytes patterns.

实例:

# 无分组
        r = re.match("h\w+", origin)
        print(r.group())     # 获取匹配到的全部结果
        print(r.groups())    # 获取模型中匹配到的分组结果
        print(r.groupdict()) # 获取模型中匹配到的分组结果

        # 有分组

        # 为什么要有分组?提取匹配成功的指定内容(先匹配成功所有正则,再匹配成功的局部内容提取出来)

        r = re.match("h(\w+).*(?P<name>\d)$", origin)
        print(r.group())     # 获取匹配到的全部结果
        print(r.groups())    # 获取模型中匹配到的分组结果
        print(r.groupdict()) # 获取模型中匹配到的分组中全部执行了key的组

search

# search,浏览整个字符串去匹配第一个,未匹配成功返回None
# search(pattern, string, flags=0)

实例:

# 无分组

        r = re.search("a\w+", origin)
        print(r.group())     # 获取匹配到的全部结果
        print(r.groups())    # 获取模型中匹配到的分组结果
        print(r.groupdict()) # 获取模型中匹配到的分组结果

        # 有分组

        r = re.search("a(\w+).*(?P<name>\d)$", origin)
        print(r.group())     # 获取匹配到的全部结果
        print(r.groups())    # 获取模型中匹配到的分组结果
        print(r.groupdict()) # 获取模型中匹配到的分组中全部执行了key的组

findall

# findall,获取非重复的匹配列表;若是有一个组则以列表形式返回,且每个匹配均是字符串;若是模型中有多个组,则以列表形式返回,且每个匹配均是元祖;
# 空的匹配也会包含在结果中
#findall(pattern, string, flags=0)

实例:

# 无分组
        r = re.findall("a\w+",origin)
        print(r)

        # 有分组
        origin = "hello alex bcd abcd lge acd 19"
        r = re.findall("a((\w*)c)(d)", origin)
        print(r)

sub

# sub,替换匹配成功的指定位置字符串
 
sub(pattern, repl, string, count=0, flags=0)
# pattern: 正则模型
# repl   : 要替换的字符串或可执行对象
# string : 要匹配的字符串
# count  : 指定匹配个数
# flags  : 匹配模式

实例:

# 与分组无关

        origin = "hello alex bcd alex lge alex acd 19"
        r = re.sub("a\w+", "999", origin, 2)
        print(r)

split

# split,根据正则匹配分割字符串
 
split(pattern, string, maxsplit=0, flags=0)
# pattern: 正则模型
# string : 要匹配的字符串
# maxsplit:指定分割个数
# flags  : 匹配模式

实例:

# 无分组
        origin = "hello alex bcd alex lge alex acd 19"
        r = re.split("alex", origin, 1)
        print(r)

        # 有分组
        
        origin = "hello alex bcd alex lge alex acd 19"
        r1 = re.split("(alex)", origin, 1)
        print(r1)
        r2 = re.split("(al(ex))", origin, 1)
        print(r2)

经常使用正则表达式:

IP:
^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$
手机号:
^1[3|4|5|8][0-9]\d{8}$
邮箱:
[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+
相关文章
相关标签/搜索