python自动化开发 day07

Author:@南非波波

课程大纲:

day06

http://www.cnblogs.com/alex3714/articles/5188179.html

day07

http://www.cnblogs.com/alex3714/articles/5213184.html

一、类的多态、继承

类的多态:统一接口调用

#!/usr/bin/env python
# -*- coding:utf-8 -*-
class Animal:
    def __init__(self, name):    # Constructor of the class
        self.name = name
    def talk(self):              # Abstract method, defined by convention only
        raise NotImplementedError("Subclass must implement abstract method")
    hobbie = 'ddd'
class Cat(Animal):
    def talk(self):
        return 'Meow!'
class Dog(Animal):
    def talk(self):
        return 'Woof! Woof!'

animals = [Cat('Missy'),
           Dog('Lassie')]

for animal in animals:
    print(animal.name + ': ' + animal.talk())

类的方法:示例

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
class Animal(object):
    '''
    定义一个动物类
    '''
    def __init__(self,name):
        self.name = name
        self.__num = None #定义成私有变量,只能在类中访问

    # def talk(self):
    #     print("%s is talking!" % self.name)
    hobbie = "shen" #类变量,静态字段
    @classmethod  #类方法,不能访问实例变量
    def talk(self):
        print("%s is talking!" % self.hobbie)
    # def work(self):
    #     print("%s is working!" % self.name)

    @staticmethod #静态方法,不能访问类变量和实例变量
    def work():
        print("It is working!")

    # def walk(self):
    #     print("%s is walking!" % self.name)
    @property #把方法编程静态属性
    def walk(self,num):
        return self.__num
    @walk.setter #传值
    def walk(self,num):
        self.__num = num
        print(self.__num)
    @walk.deleter  #删值
    def walk(self):
        print("del num")
c = Animal("swht")
# c.talk()
# c.work()
c.walk = 3
del c.walk
print("OUT:",c._Animal__num)  #特例情况下可以通过这种方式访问私有变量

经典类与新式类

经典类和新式类区别:

经典类:使用深度优先进行继承
新式类:使用广度优先进行继承

另外:经典类和新式类在python-3.X平台上会默认使用广度优先进行继承,而在python-2.X中则体现上述区别

示例代码:

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''

class A:
    print("A")
    def f2(self):
        print("f2 from A")
class B(A):
    print("B")
    def f1(self):
        print("f1 from B")
    def f2(self):
        print("f2 from B")
class C(A):
    print("C")
    def f2(self):
        print("f2 from C")

class D(B,C):
    pass

d = D()
d.f1()
d.f2()

'''
广度优先算法继承。先将B类中的f2()注释掉,D自动继承C.f2(),如果再将C类中的f2(),D自动继承A.f2()
'''

类的特殊成员

__doc__:查看类的注释
__init__:构造方法,通过类创建对象时,自动触发执行。
__module__:表示当前操作的对象在那个模块
__class__:表示当前操作的对象的类是什么
__del__:析构方法,解释器进行垃圾回收时自动触发
__call__:对象加()执行call方法
__new__:实例化时new方法执行了__init__
__metaclass__:通过改写metaclass方法达到构建自己需要的类的目的
__dict__:以字典的形式显示类对象中的成员。使用场景:查看类中有多少成员(只显示类变量,不显示实例变量)
__str__:如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。
__iter__:用于迭代器,之所以列表、字典、元组可以进行for循环,是因为类型内部定义了 __iter__ 

示例:

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''

class People(object):
    '''
    定义一个人类
    '''
    def __init__(self,name,age):
        '''
        定义属性
        :param name: 人类的名字
        :param age: 人类的年龄属性
        :return:
        '''
        self.name = name
        self.age = age

    def china_man(self):
        pass

chinese = People("swht",27)
#__doc__:查看类的注释
print(chinese.__doc__) #  定义一个人类
#__dict__:以字典的形式显示类对象中的成员。使用场景:查看类中有多少成员(只显示类变量,不显示实例变量)
print(chinese.__dict__) #{'age': 27, 'name': 'swht'}
#__module__:表示当前操作的对象在那个模块
print(chinese.__module__) #__main__
#__class__:表示当前操作的对象的类是什么
print(chinese.__class__) #<class '__main__.People'>

构造类的方法

http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python

一句话构建一个类

Foo = type('Foo',(object,), {'func': func}) 
    #type第一个参数:类名
    #type第二个参数:当前类的基类
    #type第三个参数:类的成员

反射方法

hasattr:判断实例中是否存在指定输入的方法

hasattr(server,sys.argv[1])  返回值是布尔型 True or False

getattr:获取实例中的方法

func = getattr(server,sys.argv[1])  获取对象方法的内存地址

setattr:将自定义的某个方法设定到特定实例中去使用

setattr(server,'run',test_run) 将特定方法test_run绑定给实例server,并重命名为run方法
server.run()  实例server可以指定调用方法run

delattr:删除实例的成员变量或者类的方法,不能删除实例的方法

#delattr可以删除类的方法、实例的成员变量
# delattr(server,'start') #尝试删除实例的方法是错误的
# delattr(server,"host") #删除实例的变量
# delattr(Webserver,'start')
# server.start() #AttributeError: 'Webserver' object has no attribute 'start'

完整示例代码:

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''

import sys
class Webserver(object):
    '''
    定义一个web server启动、关闭类
    '''
    def __init__(self,host,port):
        '''
        初始化类
        :param host: 主机地址
        :param port: 主机端口号
        :return:
        '''
        self.host = host
        self.port = port
    def start(self):
        '''
        服务启动方法
        :return:
        '''
        print("service is starting...")

    def stop(self):
        '''
        服务停止方法
        :return:
        '''
        print("service is stopping ...")

    def restart(self):
        '''
        服务重启方法
        :return:
        '''
        self.stop()
        self.start()

#定义一个特殊运行的函数,绑定到实例server上去
def test_run():
    print("测试运行...")

server = Webserver("localhost",80)
if hasattr(server,sys.argv[1]):
    func = getattr(server,sys.argv[1])
    func()
#setattr主要作用是将一个单独定义的函数添加到实例中,对于类或者其他实例而言,该函数对其不生效
setattr(server,'run',test_run)
server.run()

#delattr可以删除类的方法、实例的成员变量
# delattr(server,'start') #尝试删除实例的方法是错误的
# delattr(server,"host") #删除实例的变量
# delattr(Webserver,'start')
# server.start() #AttributeError: 'Webserver' object has no attribute 'start'

二、socket网络编程

简单实现C/S交互实例:

示例代码:

实现简单的client与server端数据交互(一句话)

socket_server

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''

import socket

ip_port = ("127.0.0.1",5000)
sk = socket.socket()
sk.bind(ip_port)
sk.listen(5)

while True:
    print("南非波波server is Listening....")
    conn,addr = sk.accept()
    client_data = conn.recv(1024)
    print(str(client_data,"utf8"))
    conn.sendall(bytes("落花不是无情物,化作春泥更护花!","utf8"))
    conn.close()

socket_client

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''

import socket
ip_port = ("127.0.0.1",5000)

sk = socket.socket()
sk.connect(ip_port)

sk.sendall(bytes("夕阳无限好,只是近黄昏","utf8"))

server_reply = sk.recv(1024)
print(str(server_reply,"utf8"))
sk.close()

改善代码1:

实现多个client与server进行串行交互

socket-server1

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''

import socket

ip_port = ("127.0.0.1",5000)
sk = socket.socket()
sk.bind(ip_port)
sk.listen(5)

while True:
    print("南非波波server is Listening....")
    conn,addr = sk.accept()
    client_data = conn.recv(1024)
    print(str(client_data,"utf8"))
    # conn.sendall(bytes("落花不是无情物,化作春泥更护花!","utf8"))
    while True:
        try:
            client_data = conn.recv(1024)
            if not client_data:
                break
            print("recv:",str(client_data,"utf8"))
            conn.send(client_data)
        except Exception:
            print("客户端断开!")
            break
    conn.close()

socket-client1

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''

import socket
ip_port = ("127.0.0.1",5000)

sk = socket.socket()
sk.connect(ip_port)

# sk.sendall(bytes("夕阳无限好,只是近黄昏","utf8"))

server_reply = sk.recv(1024)
print(str(server_reply,"utf8"))
while True:
    client_data = input(">>:").strip()
    if not client_data:
        continue
    if client_data == 'q':
        break
    sk.send(bytes(client_data,"utf8"))
    print(client_data)
sk.close()

最终代码:

实现简单的ssh命令交互,获取Linux系统的相关信息

socket-server2

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import socket
import subprocess

ip_port = ("127.0.0.1",5000)  #定义服务监听的ip地址和端口
ssh = socket.socket()
ssh.bind(ip_port) #进行地址和端口绑定
ssh.listen(5) #设定做多5个并发连接

while True:
    print("南非波波Server is waiting...")
    conn,addr = ssh.accept()
    while True:
        client_data = conn.recv(1024)  #介绍client发过来的数据,最大接收字节1024
        if not client_data: #如果client_data为空,则跳出循环
            break
        cmd = str(client_data,"utf8") #获取client_data数据并进行类型和编码转换
        print("server recv:",cmd)
        cmd_call = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE) #以原生shell命令的形式指定client的强求指定,并将结果输出到cmd_result
        cmd_result = cmd_call.stdout.read()
        if len(cmd_result) == 0: #如果命令没有结果返回,则需要给client返回一个提示,否则控制台会阻塞
            cmd_result = b"cmd execution has no output.."

        #client不能一次性接收过多的数据包,需要server端先告知client端需要传输的数据多少。然后由client端分开接收
        ack_msg = bytes("CMD_RESULT_SIZE|%s" % len(cmd_result),"utf8") #发送数据传输认证标志
        conn.send(ack_msg)
        client_ack = conn.recv(50)
        if client_ack.decode() == 'CLIENT_READY_TO_RECV':
            conn.send(cmd_result) #数据传输
    conn.close()

socket-client2

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import socket

ip_port = ("127.0.0.1",5000)
ssh_client = socket.socket()
ssh_client.connect(ip_port)

while True:
    user_input = input("ssh-client:").strip()
    if len(user_input) == 0:
        continue
    if user_input == 'q':
        break
    ssh_client.send(bytes(user_input,'utf8'))
    #ack_msg = b"CMD_RESULT_SIZE|%s" % len(cmd_result)
    server_ack_msg = ssh_client.recv(100)
    cmd_res_msg = str(server_ack_msg.decode()).split("|")
    if cmd_res_msg[0] == "CMD_RESULT_SIZE":
        cmd_res_size = int(cmd_res_msg[1])
        ssh_client.send(b"CLIENT_READY_TO_RECV")
    res = ''
    received_size = 0
    while received_size < cmd_res_size:
        server_data = ssh_client.recv(500)
        received_size += len(server_data)
        res += str(server_data.decode())
    else:
        print(res)
        print("-----------recv don----------")
ssh_client.close()

python自动化开发 day06

Author:@南非波波

课程大纲:

day05

http://www.cnblogs.com/alex3714/articles/5161349.html

day06

http://www.cnblogs.com/alex3714/articles/5188179.html

一、模块回顾

1. os模块

2. sys模块

3. shutil模块

高级的 文件、文件夹、压缩包 处理模块

shutil.copyfileobj(fsrc, fdst[, length])

功能:将文件内容拷贝到另一个文件中,可以部分内容

shutil.copyfile(src, dst)

功能:仅拷贝文件

shutil.copymode(src, dst)

功能:仅拷贝权限,内容、组、用户均不变

shutil.copystat(src, dst)

功能:拷贝状态的信息,包括:mode bits, atime, mtime, flags

shutil.copy(src, dst)

功能:拷贝文件和权限

shutil.copy2(src, dst)

功能:拷贝文件和状态信息

1. zipfile


2. tarfile

4. shelve模块

二次封装pickle模块功能,对比pickle而言,shelve实现了按照‘键’来取值

示例:

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import shelve

name = ['swht','shen','test']
class Test(object):
    def __init__(self,n):
        self.n = n
t1 = Test(1234)
t2 = Test(123456)

#存数据
# shelve_file = shelve.open('ret.txt')
# shelve_file['use'] = name
# shelve_file['t1'] = t1
# shelve_file['t2'] = t2
# shelve_file.close()

#取数据
shelve_load = shelve.open('ret.txt')
a = shelve_load.get('use')
print(a)
b = shelve_load.get('t1')
print(b.n)
c = shelve_load.get('t2')
print(c.n)
shelve_load.close()

5.configparser模块

示例:

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import configparser

#生成文档
#["DEFAULT"]是一个全局模块,对所有的模块生效
'''
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9'}

config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'     # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
   config.write(configfile)
'''

#查询
'''
config = configparser.ConfigParser()
config.read('example.ini')
print(config.sections())  #['bitbucket.org', 'topsecret.server.com']
if 'bitbucket.org' in config:
    print('True')
print("['bitbucket.org']['User']:",config['bitbucket.org']['User'])
print("['bitbucket.org']['Compression']:",config['bitbucket.org']['Compression'])
for key in config['bitbucket.org']:
    print(key)
'''
#读
'''
config = configparser.ConfigParser()
config.read('example.ini')
secs = config.sections()
print(secs) #['bitbucket.org', 'topsecret.server.com']

options = config.options('topsecret.server.com')
print(options) #['host port', 'forwardx11', 'compression', 'serveraliveinterval', 'compressionlevel']

item_list = config.items('bitbucket.org')
print(item_list) #[('compression', 'yes'), ('serveraliveinterval', '45'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]

val = config.get('bitbucket.org','compression')
print(val)
'''

#改写
config = configparser.ConfigParser()
config.read('example.ini')

#实现从原来的文件中读取,删除[bitbucket.org]模块后将其他内容写到example_new.ini文件中
# sec = config.remove_section('bitbucket.org')
# config.write(open('example_new.ini', "w"))

#添加[swht]模块
# sec = config.has_section('swht')
# sec = config.add_section('swht')
# config.write(open('example_new1.ini', "w"))

6. hashlib模块

该模块提供了多个算法对字符串进行加密操作。

示例代码:

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import hashlib

'''
#md5加密
md5num = hashlib.md5()
md5num.update(b"shendiaoxia1278@sohu.com")
print(md5num.hexdigest()) #7e023c9fafc96423da854e4923f466a1
'''

'''
#sha1加密
sha1num = hashlib.sha1()
sha1num.update(b"shendiaoxia1278@sohu.com")
print(sha1num.hexdigest()) #dd8d5deaa16c2dde03785aac99943f8f75bfaba9
'''

'''
#sha256加密
hash = hashlib.sha256()
hash.update(b"shendiaoxia1278@sohu.com")
print(hash.hexdigest()) #14b03e2271da2cc9b0cc3ff73727c6d3ba6ba17077470a92162f7b46c9d1d968
'''

'''
#sha384加密
hash = hashlib.sha384()
hash.update(b"shendiaoxia1278@sohu.com")
print(hash.hexdigest()) #a27bbc0d66d6b8b00a7ebfcad662ebed385fe2098898dfe23b88ffa88e1b6565d82e7eee5c9950c90231d0c0aa286e00
'''

'''
#sha512加密
hash = hashlib.sha512()
hash.update(b"shendiaoxia1278@sohu.com")
print(hash.hexdigest()) #42bb1886bba49373c8f8177fba32a58a1f31af7272219789db52776428789f4a39970da9a36fdef6ab76651ed9f07e0fa140e4fa7dd325cb52559389bb80ceab
'''

高级加密代码

'''
# import hashlib

# ######## md5 #######
hash = hashlib.md5(b'898oaFs09f')
hash.update(b"shendiaoxia1278@sohu.com")
print(hash.hexdigest()) #2aa29d812ca08b39d96f9441775420ba
'''

'''
import hmac

#可以使用在用户登录的时候,使用用户输入的用户名和密码进行加密后作为用户的密码

hash = hmac.new(b"shendiaoxia1278@sohu.com")
hash.update(b"swht")
print(hash.hexdigest()) #c65d9bc3f37d6cfb9a9c959a18463bf4

'''

7. subprocess模块

1. python2.7

    import subprocess
    #默认状态shell = False,必须使用一个列表的方式将shell命令传递进去
    ret = subprocess.call(["ls", "-l"], shell=False)
    #使用shell = True告诉subprocess模块对用户传入的shell命令不转义,即使用原生shell命令
    ret = subprocess.call("ls -l", shell=True)


2. python3.5

8. logging模块

示例:

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import logging

# logging.warning("user [swht] is start the systerm!")
# logging.critical("server is down!")
#创建日志
logger = logging.getLogger('[Test-Log]')
logger.setLevel(logging.DEBUG) #全局级别优先级较高

#创建一个控制台的handler并设置日志级别
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

#创建一个文件的handler并设置日志级别
fh = logging.FileHandler("access.log")
fh.setLevel(logging.WARNING)
#创建日期格式

fomatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s',datefmt='%Y-%m-%d %H:%M:%S')

#add formatter to ch and fh
ch.setFormatter(fomatter)
fh.setFormatter(fomatter)

logger.addHandler(ch)
logger.addHandler(fh)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

#输出格式:
'''
2016-02-20 16:53:27 [Test-Log] DEBUG debug message
2016-02-20 16:53:27 [Test-Log] INFO info message
2016-02-20 16:53:27 [Test-Log] WARNING warn message
2016-02-20 16:53:27 [Test-Log] ERROR error message
2016-02-20 16:53:27 [Test-Log] CRITICAL critical message
'''

二、面向对象编程

1. 面向对象的介绍

1.    不要写重复的代码
2.    代码易扩展,程序遵循易读、易改的原则

2. 面向对象的特性

1.    封装
2.    继承
    1.    基类或父类或超类
    2.    子类或派生类
    一般情况下,一个子类只能有一个基类,但在python中,一个子类是可以继承多个基类,实现多重继承,可以通过多级继承来实现;继承的过程就是从一般到特殊的过程
3.    多态
    实现接口的重用

3. 类、方法

类 class

示例:

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
class Role(object):
    def __init__(self,name,role,weapon,life_value):
        self.name = name
        self.role = role
        self.weapon = weapon
        self.life_value = life_value
    def buy_weapon(self,weapon):
        self.weapon = weapon
        print("%s 成功购买[%s]" % (self.name,weapon))

#实例化
p1 = Role('swht','p','A11',100)
t1 = Role('shen','t','A11',100)

print("p1[weapon]初始值:",p1.weapon)
print("t1[weapon]初始值:",t1.weapon)

#买枪行为
p1.buy_weapon("AK65")
t1.buy_weapon("AK60")

print("p1[weapon]当前值:",p1.weapon)
print("t1[weapon]当前值:",t1.weapon)

作业:

模拟人生游戏

    1.    至少有两个不同的角色
    2.    玩的过程中,必须有交互
    3.    根据不同的交互产生不同的行为
    4.    一定要用到面向对象编程的语法及思想

python自动化开发 day05

Author:@南非波波

课程大纲:

day04

http://www.cnblogs.com/alex3714/articles/5143440.html

day05

http://www.cnblogs.com/alex3714/articles/5161349.html

一、正则深入

re

匹配数字开头

import re
#匹配以数字开头
p = re.compile("^[0-9]") #使用compile进行编译正则表达式,在大量匹配处理的时候非常有效
m = p.match("14534Abc")
print(m.group()) #输出结果:1
'''
m = re.match("^[0-9]","14534Abc")
print(m.group()) #输出结果:1
'''

匹配数字、字母等开头

import re
#匹配以数字和字母开头
p = re.compile("^[0-9A-Za-z]")
m = p.match("AK14534Abc")
print(m.group()) #输出结果:A

匹配IP地址:

#匹配IP地址
string = '180.115.183.45 - - [03/Feb/2016:10:35:50 +0800] "CONNECT imppl.tradedoubler.com:443 HTTP/1.0" 400 172 "-" "-"'
p = re.compile("([0-9]{1,3}\.){3}\d{1,3}")
ip = p.match(string).group()
# ip = re.match("([0-9]{1,3}\.){3}\d{1,3}",string).group()
print(ip)

正则表达式常用5种操作

re.match(pattern,string) #从头匹配

re.search(pattern,string) #匹配整个字符串,直到找到一个匹配

re.split() #将匹配到的格式当做分隔点对字符串分成列表类型

示例:
import re
string = "2016 02 02  00:26:35 Statistic_Svncommit.py[line:50] INFO ['A6909850956019', 'A6997448878578', 'A6909712867884', 'A6996408725555', 'A6908651568946', 'A6996150172637', 'A6909747538711', 'A6994084740002', 'A6908427730549', 'A6982187752993', 'A6909861345295', 'A6909860252981', 'A6905214359647', 'A6995115894134']"
strlist = re.search("\[\'.*?\'\]",string).group().lstrip("[").rstrip("]")
list1 = re.sub("[\'' ']","",strlist).split(",")
print(list1)

返回结果:['A6909850956019', 'A6997448878578', 'A6909712867884', 'A6996408725555', 'A6908651568946', 'A6996150172637', 'A6909747538711', 'A6994084740002', 'A6908427730549', 'A6982187752993', 'A6909861345295', 'A6909860252981', 'A6905214359647', 'A6995115894134']
列表类型

m = re.split("[0-9]", "swht1swht2jack3helenrachel8")
print(m) #['swht', 'swht', 'jack', 'helenrachel', '']

re.findall() # 找到所有要匹配的字符并返回列表格式

示例:
import re
string = "sdsdss(welcome)dff(china)"
m = re.findall('\(.*?\)',string) #匹配所有以(开头和以)结尾的字符串,返回类型为list
print(m) #['(welcome)', '(china)']
print(type(m))  #<class 'list'>

re.sub(pattern, repl, string, count,flag) # 替换匹配到的字符

示例:
import re
string = "sdsdss(welcome)dff(china)"
m = re.sub("\(|\)","\"",string) #匹配"("或者")",然后将其替换成双引号
print(m) #sdsdss"welcome"dff"china"
print(type(m)) #<class 'str'>

模式

re.I #大小写不敏感

import rz
string = "swht"
m = re.search("[A-Z]",string,flags = re.I)
print(m.group()) #s

匹配手机号:

import re
string = "sdssaawa15865921165sdsdscf"
m = re.search("(1)([358]\d{9})",string)
print(m.group())

匹配IP地址:

import re
ip_addr = "inet 192.168.60.223 netmask 0xffffff00 broadcast 192.168.60.255"
IP = re.search("(([1-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-5][0-5])\.){3}[0-9]{1,3}",ip_addr)
print(IP.group()) #192.168.60.223

匹配邮箱地址:

import re
emailstr = "qingbo.song@gmail.com www.baidu.com"
email = re.search("^[a-z]([0-9a-z]|\.){4,20}@[0-9a-z]{0,10}\.[0-9a-z]{0,8}",emailstr)
print(email.group()) #qingbo.song@gmail.com

#只匹配gmail邮箱
import
emailstr = "qingbo.song@gmail.com www.baidu.com"
email = re.search("^[a-z]([0-9a-z]|\.){4,20}@gmail\.com",emailstr)
if email:
    print(email.group()) #qingbo.song@gmail.com
else:
    print("系统只接受gamil邮箱注册,感谢你的支持!")

二、冒泡排序算法

示例代码:
#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''

li = [11,78,45,12,90,34,56]

# for m in range(1,len(li)):
#     for i in range(len(li) - 1):
#         if li[i] > li[i+1]:
#             temp = li[i]
#             li[i] = li[i+1]
#             li[i+1] = temp
# print(li)

for m in range(len(li) - 1):
    for n in range(m+1,len(li)):
        if li[m] > li[n]:
            temp = li[m]
            li[m] = li[n]
            li[n] = temp
print(li) #[11, 12, 34, 45, 56, 78, 90]

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''

data = [11,78,45,12,90,34,56]
for i in range(1,len(data)):
    for j in range(len(data) - i):
        if data[j] > data[j+1]:
            tmp = data[j]
            data[j+1] = data[j]
            data[j] = tmp
print(data)

三、模块

模块介绍

模块:用一坨代码实现了某个功能的代码集合。
类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来处理和代码间的耦合。可能需要多个.py的文件组成。

模块类型:
    1. 自定义模块
    2. 内置标准模块(标准库)
    3. 开源模块
        1. 下载:
            1. yum
            2. apt-get
            3. pip
            4. easy_install
            5. 源码编译安装 python stup.py install

导入模块

import module
from module.xx.xx import xx
from module.xx.xx import xx as rename  
#不推荐下面的导入方式,如果被导入的模块中含有与当前文件中相同名称的函数,容易产生调用混乱。
from module.xx.xx import * 

四、自定义模块

模块框架

1. backend
    1. logic
        handle.py
            #!/usr/local/env python3
            '''
            Author:@南非波波
            Blog:http://www.cnblogs.com/songqingbo/
            E-mail:qingbo.song@gmail.com
            '''
            from backend.database.sql_select import select
            def home():
                print("welcome to home page!")
                q_data = select("user","test")
                print("query res:%s" % q_data)

            def tv():
                print("welcome to tv page!")

            def moive():
                print("welcome to moive page!")
    2. database
        1. sql_select.py
            #!/usr/local/env python3
            '''
            Author:@南非波波
            Blog:http://www.cnblogs.com/songqingbo/
            E-mail:qingbo.song@gmail.com
            '''
            '''
            增加模块的路径。下面的语句增加的是dj路径
            该功能解决的是在子模块中的文件单独调试的时候无法获取父模块路径,导致在导入其他模块的时候报错
            '''
            import sys,os
            #获取dj的绝对路径
            base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
            #将获取的路径添加到系统环境变量中
            sys.path.append(base_dir)


            from config import settings
            from backend.database.user_auth import db_auth

            def select(table,column):
                if db_auth(settings):
                    if table == "user":
                        user_info = {
                            "001":["swht",24,"yunwei"],
                            "002":["shen",26,"dba"],
                            "003":["test",28,"student"],
                        }
                        return user_info
        2. user_auth.py
            #!/usr/local/env python3
            '''
            Author:@南非波波
            Blog:http://www.cnblogs.com/songqingbo/
            E-mail:qingbo.song@gmail.com
            '''
            def db_auth(configs):
                if configs.DATABASES["user"] == "root" and configs.DATABASES["password"] == 123:
                    print("验证通过!")
                    return True
                else:
                    print("验证错误!")

2. frontend
3. config
    settings
        #!/usr/local/env python3
        '''
        Author:@南非波波
        Blog:http://www.cnblogs.com/songqingbo/
        E-mail:qingbo.song@gmail.com
        '''

        DATABASES = {
            "engine":"mysql",
            "host":"localhost",
            "port":3306,
            "user":"root",
            "password":123,
        }
4. user_main.py
    #!/usr/local/env python3
    '''
    Author:@南非波波
    Blog:http://www.cnblogs.com/songqingbo/
    E-mail:qingbo.song@gmail.com
    '''

    from backend.logic import handle

    handle.home()

五、标准模块

参考:http://www.cnblogs.com/wupeiqi/articles/4963027.html

time & datetime模块

import time
import datetime

#作用:计算一个程序从执行到结束用的时间 
print(time.clock()) #返回处理器时间,3.3开始已废弃
print(time.process_time()) #返回处理器时间,3.3开始已废弃

#获取系统的当前时间,从1970年1月1日0:00到当前时间的秒数
print(time.time()) #返回当前系统时间戳

#格式化输出的时间
print(time.ctime()) #输出Tue Jan 26 18:23:48 2016 ,当前系统时间
print(time.ctime(time.time()-86640)) #将时间戳转为字符串格式,输出昨天的时间Tue Jan 25 18:23:48 2016

#time.struct_time(tm_year=2016, tm_mon=2,c=48, tm_wday=5, tm_yday=44, tm_isdst=0)
#gmtime是从零时区算起的格林时间
print(time.gmtime(time.time()-86640)) #将时间戳转换成struct_time格式
#当前时间,是按照系统当前时区算起的
print(time.localtime(time.time()-86640)) #将时间戳转换成struct_time格式,但返回 的本地时间
print(time.mktime(time.localtime())) #与time.localtime()功能相反,将struct_time格式转回成时间戳格式
#time.sleep(4) #sleep

#格式化输出时间
print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将struct_time格式转成指定的字符串格式
#time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
#'2016-02-14 12:45:49'

print(time.strptime("2016-01-28","%Y-%m-%d") ) #将字符串格式转换成struct_time格式

#datetime module

#将时间戳转换成日期格式
print(datetime.date.today()) #输出格式python2 2016-01-26  python3:datetime.date(2016, 2, 14)
print(datetime.date.fromtimestamp(time.time()-864400) ) #2016-01-16 将时间戳转成日期格式
current_time = datetime.datetime.now() #
print(current_time) #输出2016-01-26 19:04:30.335935
print(current_time.timetuple()) #返回struct_time格式

#datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
#将当前的时间替换成输入的时间
print(current_time.replace(2014,9,12)) #输出2014-09-12 19:06:24.074900,返回当前时间,但指定的值将被替换

str_to_date = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") #将字符串转换成日期格式
new_date = datetime.datetime.now() + datetime.timedelta(days=10) #比现在加10天
new_date = datetime.datetime.now() + datetime.timedelta(days=-10) #比现在减10天
new_date = datetime.datetime.now() + datetime.timedelta(hours=-10) #比现在减10小时
new_date = datetime.datetime.now() + datetime.timedelta(seconds=120) #比现在+120s
print(new_date)

random模块

产生随机数

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import random

#产生随机小数
print(random.random())
'''
0.8426794741026359
0.8703558703687821
'''

#产生随机整数
print(random.randint(1,10))
print(random.randrange(1,10))
'''
1
9
'''

生成随机验证码

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
'''
生成n位随机数,包含大写字母和数字
'''
import random
def checkcode(n):
    checkcode = ''
    for i in range(n):
        current = random.randrange(0,4)
        if current != i:
            tmp = chr(random.randint(65,90))
        else:
            tmp = random.randint(0,9)
        checkcode += str(tmp)
    return checkcode

print(checkcode(6))

os模块

提供对操作系统进行调用的接口

os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
os.curdir  返回当前目录: ('.')
os.pardir  获取当前目录的父目录字符串名:('..')
os.makedirs('dirname1/dirname2')    可生成多层递归目录
os.removedirs('dirname1') 删除空的目录,或多级空目录
os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove()  删除一个文件
os.rename("oldname","newname")  重命名文件/目录,或者移动,相当于shell命令mv
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命令,直接显示,只是单个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所指向的文件或者目录的最后修改时间

sys模块

sys.argv           命令行参数List,第一个元素是程序本身路径
sys.exit(n)        退出程序,正常退出时exit(0)
sys.version        获取Python解释程序的版本信息
sys.maxint         最大的Int值
sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform       返回操作系统平台名称
sys.stdout.write('please:')
val = sys.stdin.readline()[:-1] #输入一行内容,减去后面的最后一个\n

使用sys和time模块生成进度条

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
'''
生成进度条。调用函数输入的参数为进度条长度
'''
import sys,time
def processbar(rangenum):
    for i in range(rangenum):
        if i == 0:
            sys.stdout.write("0%[#")
        elif i == rangenum - 1:
            sys.stdout.write("#]100%")
        else:
            sys.stdout.write("#")
            #刷新缓存,使其实时显示出来
            sys.stdout.flush()
            time.sleep(0.5)

processbar(16)

json 和 pickle

json和pickle是用于序列化的两个模块:

json:用于处理字符串和python数据类型间的转换
pickle:用于处理python特有类型和python数据类型间的转换

json

json模块提供了四个功能:dumps、dump、loads、load
json在所有的语言中都通用,存取的直接字符

pickle

pickle模块提供了四个功能:dumps、dump、loads、load
在python中独有一个模块,存取二进制字符
不仅仅可以序列化简单的字符、列表、字典,还能序列化函数、类以至于整个程序

关于dump和dumps的区别

dump直接将序列化后的字符写到文件中,dumps是将序列化后的字符先赋给一个变量,然后再有write方法将其写入到文件中

关于load和loads的区别

load直接从文件中读取内容,loads是从内存中获取文件的内容

shutil模块

高级的 文件、文件夹、压缩包 处理模块

shutil.copyfileobj(fsrc, fdst[, length])

功能:将文件内容拷贝到另一个文件中,可以部分内容

shutil.copyfile(src, dst)

功能:仅拷贝文件

shutil.copymode(src, dst)

功能:仅拷贝权限,内容、组、用户均不变

shutil.copystat(src, dst)

功能:拷贝状态的信息,包括:mode bits, atime, mtime, flags

shutil.copy(src, dst)

功能:拷贝文件和权限

shutil.copy2(src, dst)

功能:拷贝文件和状态信息

作业需求:

模拟实现一个ATM + 购物商城程序

额度 15000或自定义
实现购物商城,买东西加入 购物车,调用信用卡接口结账
可以提现,手续费5%
每月22号出账单,每月10号为还款日,过期未还,按欠款总额 万分之5 每日计息
支持多账户登录
支持账户间转账
记录每月日常消费流水
提供还款接口
ATM记录操作日志
提供管理接口,包括添加账户、用户额度,冻结账户等。

python自动化开发 day04

Author:@南非波波

课程大纲:

day03

http://www.cnblogs.com/wupeiqi/articles/5133343.html

day04

http://www.cnblogs.com/alex3714/articles/5143440.html

一、迭代器 && 生成器

1.迭代器

迭代器是访问集合元素的一种方式。迭代器只能往前不能往后。迭代器对象从集合的第一个集合开始访问,直到所有的元素被访问完。
优点:不需要事先准备整个迭代过程中的所有元素

测试代码

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''

names = iter(['swht','shen','jack'])
print(names)
print(names.__next__())
print(names.__next__())
print(names.__next__())

返回结果:
    <list_iterator object at 0x000000000114C7B8>
    swht
    shen
    jack

2.生成器

定义:generator,一个函数调用时返回一个迭代器,那这个函数就叫做生成器。

作用:yield实现函数中断,并保存函数中断时的状态。中断后,程序可以继续执行下面的代码,而且可以随时可以回头再执行之前中断的函数。
    可以通过yield实现在单线程的情况下实现并发运算的效果

测试代码

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''

def money(num):
    while num > 0:
        print("取款100元!")
        num -= 100
        yield 100
        print("你当前还有%s元" % num)

ATM = money(500)
print(type(ATM))
print(ATM.__next__())
print(ATM.__next__())
print("吃包子....")
print(ATM.__next__())
print(ATM.__next__())

返回结果:
    <class 'generator'>
    取款100元!
    100
    你当前还有400元
    取款100元!
    100
    吃包子....
    你当前还有300元
    取款100元!
    100
    你当前还有200元
    取款100元!
    100

实现异步:【生产者-消费者模型】

yield参数可以实现返回参数和接收参数,使用send方法可以将值传递到生成器中去

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''

import time
def consumer(name):
    print("%s 开始准备吃包子!" % name)
    while True:
        baozi = yield #yield可以返回一个值,也可以接收一个值
        print("第[%s]波包子来了,被[%s]吃了!" % (baozi,name))

def producer(name):
    c1 = consumer('swht')
    c2 = consumer('shen')
    c1.__next__()
    c2.__next__()
    print("==%s开始准备做包子!==" % name)
    for i in range(10):
        time.sleep(1)
        print("**%s做了两个包子!**" % name)
        c1.send(i) #使用send方法将值传递给yield
        c2.send(i)

producer('alex')

返回结果:

swht 开始准备吃包子!
shen 开始准备吃包子!
==alex开始准备做包子!==
**alex做了两个包子!**
第[0]波包子来了,被[swht]吃了!
第[0]波包子来了,被[shen]吃了!
**alex做了两个包子!**
第[1]波包子来了,被[swht]吃了!
第[1]波包子来了,被[shen]吃了!
**alex做了两个包子!**
第[2]波包子来了,被[swht]吃了!
第[2]波包子来了,被[shen]吃了!
**alex做了两个包子!**
第[3]波包子来了,被[swht]吃了!
第[3]波包子来了,被[shen]吃了!
**alex做了两个包子!**
第[4]波包子来了,被[swht]吃了!
第[4]波包子来了,被[shen]吃了!
**alex做了两个包子!**
第[5]波包子来了,被[swht]吃了!
第[5]波包子来了,被[shen]吃了!
**alex做了两个包子!**
第[6]波包子来了,被[swht]吃了!
第[6]波包子来了,被[shen]吃了!
**alex做了两个包子!**
第[7]波包子来了,被[swht]吃了!
第[7]波包子来了,被[shen]吃了!
**alex做了两个包子!**
第[8]波包子来了,被[swht]吃了!
第[8]波包子来了,被[shen]吃了!
**alex做了两个包子!**
第[9]波包子来了,被[swht]吃了!
第[9]波包子来了,被[shen]吃了!

二、装饰器

装饰器又叫语法塘

装饰器调用原理

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
def login(func):
    print("To passed!")
    return func

def home(name):
    print("Welcome [%s] to home page!" % name)

def tv(name):
    print("Welcome [%s] to TV page!" % name)

def moive(name):
    print("Welcome [%s] to Moive page!" % name)

tv = login(tv)  #将tv函数的内存地址传递到login()函数中,然后将tv的内存地址返回并赋给变量tv
tv("swht") #变量调用相当于函数的调用

装饰器实现

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
def login(func): #程序执行时返回inner函数的内存地址
    def inner(*arg,**kwargs):
        print("To passed!")
        return func(*arg,**kwargs)
    return inner

def home(name):
    print("Welcome [%s] to home page!" % name)

@login
def tv(name):
    print("Welcome [%s] to TV page!" % name)

def moive(name):
    print("Welcome [%s] to Moive page!" % name)
tv("swht")

返回结果:

To passed!
Welcome [swht] to TV page!

多参数装饰器

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''

def Before(request,kargs):
    print('before')

def After(request,kargs):
    print('after')


def Filter(before_func,after_func):
    def outer(main_func):
        def wrapper(request,kargs):

            before_result = before_func(request,kargs)
            if(before_result != None):
                return before_result

            main_result = main_func(request,kargs)
            if(main_result != None):
                return main_result

            after_result = after_func(request,kargs)
            if(after_result != None):
                return after_result

        return wrapper
    return outer

@Filter(Before, After)
def Index(request,kargs):
    print('index')

Index("swht","123")

实现流程

'''
1.程序运行,读取顺序 @Filter --> Index()
2.@Filter运行机制:
    1)将Before, After传递给Filter(),执行outer();
    2)将Index传递给outer()函数,执行wrapper(),返回outer;
    3)将Index()中的两个参数request,kargs传递给wrapper()函数,执行:
        1)执行before_func()即Before()并判断返回值,打印before
        2)执行main_func()即Index()并判断返回值,打印index
        3)执行after_func()即After()并判断返回值,打印after
3.程序结束
'''

三、递归

演示递归进出过程:【栈的实现:后进先出】

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''

def calc(n):
    print(n)
    if n/2 > 1:
        res = calc(n/2)
        print('res:',res)
    print('n:',n)
    return n
calc(10)
'''
递归进入多少层,最后函数结束退出的时候就是退出多少层
'''

返回结果:

10
5.0
2.5
1.25
n: 1.25
res: 1.25
n: 2.5
res: 2.5
n: 5.0
res: 5.0
n: 10

斐波那契数列

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''

def sum(arg1,arg2,stop):
    if arg1 == 0:
        print(arg1,arg2)
    arg3 = arg1 + arg2
    print(arg3)
    if arg3 < stop:
        sum(arg2,arg3,stop)

sum(0,1,500)

返回结果:

0 1
1
2
3
5
8
13
21
34
55
89
144
233
377
610

四、二分查找

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
def binary_search(data_source,find_num):
    mid = int(len(data_source)/2)  #列表折中
    if len(data_source) >= 1: #如果列表的长度值大于1,则递归
        if data_source[mid] > find_num: #如果中间值大于查找值,这说明查找值在中间值的左侧
            print("%s\tis\tthe\tleft\tof \t%s" % (find_num,data_source[mid]))
            binary_search(data_source[:mid],find_num)
        elif data_source[mid] < find_num: #如果中间值小于查找值,这说明查找值在中间值的右侧
            print("%s\tis\tthe\tright\tof \t%s" % (find_num,data_source[mid]))
            binary_search(data_source[mid:],find_num)
        else:
            print("已经查找到\t%s" % find_num)
    else: #否则返回值,查找不到
        print("查不到该数值!")

if __name__ == "__main__":
    data = list(range(1,90000))
    binary_search(data,65535)

五、二维数组

二维数组的概念是在c、c++等语言中出现并定义,在python没有数组概念,对应的则是列表。所以我们这里称为二维数组则是对二维列表的称谓。

需求:

转换二维数组
初始列表:
    [0, 1, 2, 3]
    [0, 1, 2, 3]
    [0, 1, 2, 3]
    [0, 1, 2, 3]
    =================
转换后列表:
    [0, 0, 0, 0]
    [1, 1, 1, 1]
    [2, 2, 2, 2]
    [3, 3, 3, 3]

代码实现:

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
data = [[col for col in range(4)] for row in range(4)]
# for i in a:
#     print(i)
for col in range(4):
    for row in range(col,4):
        data[col][row],data[row][col] = data[row][col],data[col][row]
for i in data:
    print(i)
print(a)

改进型:

data = [[col for col in range(4)] for row in range(4)]
for col in range(len(data)):
    for row in data[col]:
        data[col][row],data[row][col] = data[row][col],data[col][row]
for i in data:
    print(i)

六、正则表达式

熟悉Linux环境的朋友肯定熟悉,用来操作字符或者文本文件时操作的快速匹配语言。正则表达式是用于处理字符串的强大工具,拥有自己独特的语法以及一个独立的处理引擎,效率上可能不如str自带的方法,但功能十分强大。

语法:

一般字符

匹配自身
示例:
import re

str1 = '23434sjsjdd523^&(csd#@52'
print(re.match('abc',str1))
返回值为:None #说明此时没有匹配到。
print(re.match('23',str1))
返回值为:<_sre.SRE_Match object; span=(0, 2), match='23'> #匹配到自身并返回类型

.

匹配任意除换行符'\n'外的字符,在DOALL模式中也能匹配换行符。
示例:
import re

str1 = '23434sjsjdd523^&(csd#@52'
print(re.match('.',str1))
返回结果:<_sre.SRE_Match object; span=(0, 1), match='2'> #匹配到任意字符'2'

\

转义字符,使后一个字符改变原来的意思。如果字符串中有字符*需要匹配,可以使用\*或者字符集[*]
示例:
a\\c  -->a\c

[…]

字符集(字符类).对应的位置可以是字符集中任意字符。字符集中的字符可以逐个列出,也可以给出范围,如[abc]或[a-c]。第一个字符如果是^则表示取反,如[^abc]表示不是abc的其他字符。
所有的特殊字符在字符集中都失去其原有的特殊含义。在字符集中如果要使用]、-或^,都可以在前面加上反斜杠,或把]、-放在第一个字符,把^放在非第一个字符。
示例:a[bcd]e -->abe ace ade

预定义字符:

数量词:

边界匹配:

逻辑、分组

正则表达式模块re

Python通过re模块提供对正则表达式的支持。使用re的一般步骤是先将正则表达式的字符串形式编译为Pattern实例,然后使用Pattern实例处理文本并获得匹配结果(一个Match实例),最后使用Match实例获得信息,进行其他的操作。

示例:

import re

test1 = re.compile(r'hello')  #使用re.compile编译成Pattern实例
test12 = test1.match('hello world!') #使用Pattern匹配文本,获得匹配结果,无法匹配时返回None

if test12:
    print(test12.group()) #使用test12获得分组信息
#输出  hello

#the same as top
m = re.match(r'hello', 'hello world!')
print(m.group())

match

match(string[,pos[endpos]])|re.match(patern,string[,flags]):
从string的pos下标处起尝试匹配pattern;如果pattern结束时仍可匹配,则返回一个Match对象;如果匹配过程中pattern无法匹配,或者匹配未结束就已到达endpos,则返回None。 
pos和endpos的默认值分别是0和len(sring);re.match()无法指定这两个参数,参数flags用于编译pattern时指定匹配模式。
(re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none.)
测试代码:
    m = re.match('hello', 'hello world!')
    print(m.group())
    返回值为:hello

    print(re.match('www','www.apicloud.com').span()) #在起始位置匹配
    print(re.match('com','www.apicloud.com')) #不在起始位置匹配

    返回结果:
    (0, 3)
    None

    import re

    line = "Cats are smarter than dogs"
    matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
    #.* 匹配任意字符且匹配前一个字符0或无限次
    #.*? 匹配任意字符,且匹配前一个字符0或无限次,且匹配前一个字符0次或1次
    if matchObj:
       print("matchObj.group() : ", matchObj.group())
       print("matchObj.group(1) : ", matchObj.group(1))
       print("matchObj.group(2) : ", matchObj.group(2))
    else:
       print("No match!!")

    返回结果:
    matchObj.group() :  Cats are smarter than dogs
    matchObj.group(1) :  Cats
    matchObj.group(2) :  smarter
功能:re.search 扫描整个字符串并返回第一个成功的匹配
语法:re.search(pattern, string, flags=0)
参数:pattern 匹配的正则表达式
     string  要匹配的字符串
     flags   标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。

测试代码:
    import re
    print(re.search('www', 'www.apicloud.com').span())  # 在起始位置匹配
    print(re.search('com', 'www.apicloud.com').span())         # 不在起始位置匹配
    返回结果:
    (0, 3)
    (13, 16)

    import re
    line = "Cats are smarter than dogs"
    searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
    if searchObj:
       print("searchObj.group() : ", searchObj.group())
       print("searchObj.group(1) : ", searchObj.group(1))
       print("searchObj.group(2) : ", searchObj.group(2))
    else:
       print("Nothing found!!")

    #返回结果:
    # searchObj.group() :  Cats are smarter than dogs
    # searchObj.group(1) :  Cats
    # searchObj.group(2) :  smarter

对比match和search

re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。
示例代码:
    import re
    line = "Cats are smarter than dogs"
    matchObj = re.match( r'dogs', line, re.M|re.I)
    if matchObj:
       print("match --> matchObj.group() : ", matchObj.group())
    else:
       print("match --> No match!!")

    searchObj = re.search( r'dogs', line, re.M|re.I)
    if searchObj:
       print("search --> searchObj.group() : ", searchObj.group())
    else:
       print("search --> No search!!")

    #返回结果:
    # match --> No match!!
    # search --> searchObj.group() :  dogs

sub

功能:re.sub用户替换字符串中的匹配项
语法:re.sub(pattern, repl, string, max=0)
测试代码:
    import re
    phone = "2004-959-559 # This is Phone Number"
    # Delete Python-style comments
    num1 = re.sub(r' .*$', "", phone) #匹配' '空格到字符串默认的所有任意字符,删除
    print("Phone Num : ", num1)  #Phone Num :  2004-959-559   最后一个字符后面没有空格
    num2 = re.sub(r'#.*$', "", phone) #匹配#到字符串默认的所有任意字符,删除
    print("Phone Num : ", num2) #Phone Num :  2004-959-559  最后一个字符后面有一个空格

    # Remove anything other than digits
    num3 = re.sub(r'\D', "", phone) #匹配非数字字符,然后删除
    print("Phone Num : ", num3) #Phone Num :  2004959559

作业:

计算器开发

1. 实现加减乘除及拓号优先级解析
2. 用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )等类似公式后,必须自己解析里面的(),+,-,*,/符号和公式,运算后得出结果,结果必须与真实的计算器所得出的结果一致

博客地址:http://www.cnblogs.com/songqingbo/p/5168125.html

python自动化开发 day03

Author:@南非波波

课程大纲:

day2
http://www.cnblogs.com/wupeiqi/articles/5115190.html

day3
http://www.cnblogs.com/wupeiqi/articles/5133343.html

一、set集合

博客链接:http://www.cnblogs.com/songqingbo/p/5128066.html

优点:访问速度快;
     自带一套解决元素重复的解决方案

测试程序

old_dict = {
    "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#2":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
}
new_dict = {
    "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 800 },
    "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#4":{ 'hostname':'c2', 'cpu_count': 2, 'mem_capicity': 80 },
}

获取三个列表:
    1. 需要更新的列表 update_list
    2. 需要删除的列表 del_list
    3. 需要增加的列表 add_list

代码实现:
    #!/usr/local/env python3
    '''
    Author:@南非波波
    Blog:http://www.cnblogs.com/songqingbo/
    E-mail:qingbo.song@gmail.com
    '''

    old_dict = {
        "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
        "#2":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
        "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    }
    new_dict = {
        "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 800 },
        "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
        "#4":{ 'hostname':'c2', 'cpu_count': 2, 'mem_capicity': 80 },
    }

    #设置set
    old_set = set(old_dict.keys())
    new_set = set(new_dict.keys())

    #更新的set
    update_set = new_set.intersection(old_dict)
    delate_set = old_set.difference(update_set)
    add_set = new_set.difference(update_set)

    update_list = []
    del_list = []
    add_list = []
    # print(update_set)
    # print(delate_set)
    # print(add_set)
    for i in update_set:
        update_list.append({i:new_dict[i]})
        print('需要更新的列表:%s' % update_list)

    for i in delate_set:
        del_list.append({i:old_dict[i]})
        print("需要删除的列表:%s" % del_list)

    for i in add_set:
        add_list.append({i:new_dict[i]})
        print("需要增加的列表:%s" % add_list)

二、collection系列

博客链接:http://www.cnblogs.com/songqingbo/p/5137785.html

不常用功能,需要进行模块功能导入:
    import collection

Counter

常用方法测试:

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import collections

obj = collections.Counter('sjndsjkdsdmslaladsldsldms')

print("输出字符出现的次数字典:")
for k,v in obj.items():
    print("{%s:%s}" % (k,v))

print("输出每一个字符:") #遍历获取原始字符元素
for k in obj.elements():
    print(k)

print("输出前四个出现次数最多的字符:")
for k in obj.most_common(4):
    print(k)


输出结果:
    输出字符出现的次数字典:
    {s:7}
    {l:4}
    {m:2}
    {d:6}
    {k:1}
    {n:1}
    {j:2}
    {a:2}
    输出每一个字符:
    s
    s
    s
    s
    s
    s
    s
    l
    l
    l
    l
    m
    m
    d
    d
    d
    d
    d
    d
    k
    n
    j
    j
    a
    a
    输出前四个出现次数最多的字符:
    ('s', 7)
    ('d', 6)
    ('l', 4)
    ('m', 2)

__missing__

功能:对于不存在的元素,返回计数器为0
import collections
c = collections.Counter('adjsdkskdjksjaksklklakl')
c.__missing__(5)
返回结果:0

most_common

功能:获取出现次数的前几个字母排名
import collections
c = collections.Counter('adjsdkskdjksjaksklklakl')
c.most_common(3)
[('k', 7), ('s', 4), ('a', 3)]
c.most_common(8)
[('k', 7), ('s', 4), ('a', 3), ('j', 3), ('l', 3), ('d', 3)]

elements

功能:计数器中的所有元素,并且按照ascii码进行了排序
    返回一个迭代器。元素被重复了多少次,在该迭代器中就包含多少个该元素。所有元素按照字母序排序,个数小于1的元素不被包含。
import collections
c = collections.Counter('adjsdkskdjksjaksklklakl')
sorted(c.elements())
返回结果:['a', 'a', 'a', 'd', 'd', 'd', 'j', 'j', 'j', 'k', 'k', 'k', 'k', 'k', 'k', 'k','l', 'l', 'l', 's', 's', 's', 's']

计数值的访问与缺失的键

功能:默认将计数器中所有的字符认为一个键,然后统计键出现的次数,即键值。如果键不存在则返回0.
import collections
c = collections.Counter('adjsdkskdjksjaksklklakl')
>>> c['a']
3
>>> c['b']
0
>>> c['l']
3

update && subtract

功能:都是更新计数器,update是增加,subtract是减少
import collections
>>> c = collections.Counter('which')
>>> c['h']  #这里的h出现2次
2
>>> c.update('with')
>>> c
Counter({'h': 3, 'i': 2, 'w': 2, 't': 1, 'c': 1})
>>> c['h'] #这里则完成了update操作,h出现了3次
3

>>> c.subtract('with') 
>>> c
Counter({'h': 2, 'c': 1, 'i': 1, 'w': 1, 't': 0})
>>> c['h'] #这里完成subtract操作之后,h出现的次数又恢复到2次
2

del

功能:删除键
import collections
>>> c = collections.Counter('which')
>>> c['h']  #这里的h出现2次
2
>>> del c['h']
>>> c
Counter({'c': 1, 'i': 1, 'w': 1, 't': 0})
>>> c['h']  #del操作删除了键'h'
0

copy

功能:浅拷贝
import collections
>>> c = collections.Counter('which')
>>> d = c.copy()
>>> d
Counter({'h': 2, 'c': 1, 'i': 1, 'w': 1})
>>> id(c)
7150792
>>> id(d)
6511976

算术和集合操作

功能:+、-、&、|操作也可以用于Counter。其中&和|操作分别返回两个Counter对象各元素的最小值和最大值。需要注意的是,得到的Counter对象将删除小于1的元素。

常用操作

说明:Counter继承dict的所有方法,常用的操作列在下面,仅供参考

有序字典orderedDict

有序字典继承字典的一切属性,只是在顺序上是有序的。
d = collections.OrderedDict({'name':'swht','age':18})
print(d)
返回结果:OrderedDict([('name', 'swht'), ('age', 18)])
print(type(d))
返回结果:<class 'collections.OrderedDict'>

move_to_end

功能:将指定的键值对从开头移动到末尾。
d = collections.OrderedDict({'name':'swht','age':18,'address':'shandong',})
d.move_to_end('name')
print(d)
返回结果:OrderedDict([('age', 18), ('address', 'shandong'), ('name', 'swht')])

pop

功能:移除字典键值,并返回删除键值的values
d = collections.OrderedDict({'name':'swht','age':18,'address':'shandong',})
d.pop('address')
print(d)
返回结果:OrderedDict([('age', 18), ('name', 'swht')])

clear

功能:清空有序字典的值
d = collections.OrderedDict({'name':'swht','age':18,'address':'shandong',})
d.clear()
print(d)
返回结果:OrderedDict()

keys,values,items

功能:继承字典的属性,获取字典的所有键和所有值
d = collections.OrderedDict({'name':'swht','age':18,'address':'shandong',})
l1 = d.keys()
l2 = d.values()
l3 = d.items()
print(l1,l2,l3)
返回结果:odict_keys(['address', 'age', 'name']) odict_values(['shandong', 18, 'swht']) odict_items([('age', 18), ('name', 'swht'), ('address', 'shandong')])

默认字典defaultdict

defaultdict是对字典的类型的补充,他默认给字典的值设置了一个类型。创建一个默认字典,value值类型为列表.
dic = collections.defaultdict(list)

可命名元组nametuple

没有现成的类,用户需要自行创建相应的类

测试代码

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import collections
MytupleClass = collections.namedtuple("MytupleClass",['x','y','z'])
obj = MytupleClass(11,22,33)
print(obj.x,obj.y,obj.z)
返回结果:11 22 33
总结:相当于在元组的基础上增加一个key,使其成为一个类字典的样子

队列

双向队列

下面两种方法都可以创建双向列表,虽然在最初的引用的类不同,但最后创建的类型 都是collections.deque
#创建双向队列
import collections
d = collections.deque()
返回结果:<class 'collections.deque'>

#but这样创建双向队列呢
import queue
p = queue.deque()
print(type(p))
#<class 'collections.deque'>

单向队列

#创建单向队列
import queue
q = queue.Queue()
print(type(q))
#<class 'queue.Queue'>

三、深浅拷贝

博客链接:http://www.cnblogs.com/songqingbo/p/5139015.html

#对于 数字 和 字符串 而言,赋值、浅拷贝和深拷贝无意义,因为其永远指向同一个内存地址
    import copy
    a1 = 22255
    a2 = 22255
    print(id(a1),id(a2)) #3428240 3428240

#对于字典、元祖、列表 而言,进行赋值、浅拷贝和深拷贝时,其内存地址的变化是不同的。

    import copy
    #字典
    n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
    ##赋值
    n2 = n1
    print(n1,n2) #{'k1': 'wu', 'k2': 123, 'k3': ['alex', 456]} {'k1': 'wu', 'k2': 123, 'k3': ['alex', 456]}
    print(id(n1),id(n2))  #6674440 6674440 #内存地址一样
    ##浅拷贝
    n3 = copy.copy(n1)
    print(n1,n3) #{'k1': 'wu', 'k2': 123, 'k3': ['alex', 456]} {'k1': 'wu', 'k2': 123, 'k3': ['alex', 456]}
    print(id(n1),id(n3)) #6936584 12067848  #浅拷贝第一级,内存地址相同
    print(id(n1['k3']),id(n3['k3'])) #18741768 18741768
    ##深拷贝
    n4 = copy.deepcopy(n1)
    print(n1,n4) #{'k3': ['alex', 456], 'k2': 123, 'k1': 'wu'} {'k3': ['alex', 456], 'k1': 'wu', 'k2': 123}
    print(id(n1),id(n4)) #6805512 11736904
    print(id(n1['k3']),id(n4['k3'])) #7601032 7599496 #深拷贝第二级,内存地址也不相同

    #列表
    n1 = [1,2,3,4,5,[6,7],]
    ##赋值
    n2 = n1
    print(n1,n2) #[1, 2, 3, 4, 5, [6, 7]] [1, 2, 3, 4, 5, [6, 7]]
    print(id(n1),id(n2)) #18609928 18609928
    print(id(n1[5]),id(n2[5])) #18609544 18609544
    ##浅拷贝
    n3 = copy.copy(n1)
    print(n1,n3) #[1, 2, 3, 4, 5, [6, 7]] [1, 2, 3, 4, 5, [6, 7]]
    print(id(n1),id(n3)) #18609928 18232904
    print(id(n1[5]),id(n3[5])) #18609544 18609544
    ##深拷贝
    n4 = copy.deepcopy(n1)
    print(n1,n4) #[1, 2, 3, 4, 5, [6, 7]] [1, 2, 3, 4, 5, [6, 7]]
    print(id(n1),id(n4)) #18609928 18611848
    print(id(n1[5]),id(n4[5])) #18609544 18611912


    #元组
    一个小插曲:
        import copy
        n1 = (1,2,3,4,5,(6,7,),)
        #赋值
        n2 = n1
        print('n1:',n1,'n2:',n2) #n1: (1, 2, 3, 4, 5, (6, 7)) n2: (1, 2, 3, 4, 5, (6, 7))
        print(id(n1),id(n2)) #10416584 10416584
        print(id(n1[5]),id(n2[5])) #18415304 18415304
        print(type(n1),type(2)) #<class 'tuple'> <class 'int'>
        #浅拷贝
        n3 = copy.copy(n1)
        print('n1:',n1,'n3:',n3) #n1: (1, 2, 3, 4, 5, (6, 7)) n2: (1, 2, 3, 4, 5, (6, 7))
        print(id(n1),id(n3)) #10416584 10416584
        print(id(n1[5]),id(n3[5])) #18415304 18415304
        print(type(n1),type(3)) #<class 'tuple'> <class 'int'>
        #深拷贝
        n4 = copy.deepcopy(n1)
        print('n1:',n1,'n4:',n4) #n1: (1, 2, 3, 4, 5, (6, 7)) n2: (1, 2, 3, 4, 5, (6, 7))
        print(id(n1),id(n4)) #10416584 10416584
        print(id(n1[5]),id(n4[5])) #18415304 18415304
        print(type(n1),type(5)) #<class 'tuple'> <class 'int'>

再一个小插曲:
    import copy
    n1 = (1,2,3,4,5,[6,7,],)
    #赋值
    n2 = n1
    print('n1:',n1,'n2:',n2) #(1, 2, 3, 4, 5, [6, 7]) n2: (1, 2, 3, 4, 5, [6, 7])
    print(id(n1),id(n2)) #11465160 11465160
    print(id(n1[5]),id(n2[5])) #18480456 18480456
    print(type(n1),type(2)) #<class 'tuple'> <class 'int'>
    #浅拷贝
    n3 = copy.copy(n1)
    print('n1:',n1,'n3:',n3) #n1: (1, 2, 3, 4, 5, [6, 7]) n3: (1, 2, 3, 4, 5, [6, 7])
    print(id(n1),id(n3)) #11465160 11465160
    print(id(n1[5]),id(n3[5])) #18480456 18480456
    print(type(n1),type(3)) #<class 'tuple'> <class 'int'>
    #深拷贝
    n4 = copy.deepcopy(n1)
    print('n1:',n1,'n4:',n4) #n1: (1, 2, 3, 4, 5, [6, 7]) n4: (1, 2, 3, 4, 5, [6, 7])
    print(id(n1),id(n4)) #11465160 18109736
    print(id(n1[5]),id(n4[5])) #18480456 18478920
    print(type(n1),type(5)) #<class 'tuple'> <class 'int'>


出现以上问题有可能跟下面的说法有关:

案例代码

    import copy
    dic = {
        "cpu":[80,],
        "mem":[80,],
        "disk":[80,],
    }

    print("old:",dic)
    new_dic1 = copy.copy(dic)
    new_dic1["cpu"][0] = 50
    print("old:",dic)
    print("浅拷贝:",new_dic1)
    #返回结果:
    #old: {'disk': [80], 'cpu': [80], 'mem': [80]}
    #浅拷贝: {'disk': [80], 'cpu': [50], 'mem': [80]}

    new_dic2 = copy.deepcopy(dic)
    new_dic2["cpu"][0] = 60
    print("old:",dic)
    print("深拷贝:",new_dic2)
    #返回结果
    # old: {'mem': [80], 'cpu': [50], 'disk': [80]}
    # 深拷贝: {'mem': [80], 'cpu': [60], 'disk': [80]}

四、函数

博客链接:http://www.cnblogs.com/songqingbo/p/5142957.html

定义:

    #!/usr/local/env python3
    '''
    Author:@南非波波
    Blog:http://www.cnblogs.com/songqingbo/
    E-mail:qingbo.song@gmail.com
    '''
    #定义函数,作用打印一个值
    def num_print():
        n = 456
        n += 1
        print(n)
使用:

    #函数调用
    num_print()
    #将f变量指向函数num_print,然后调用f()相当于调用num_print()
    f = num_print
    f()

参数

形参:函数中一个变量,在函数执行前无意义,在函数调用时必须指定实际参数。
实参:实际参数用户传递给所调用的函数的一个变量,其值赋值到函数中的形式参数,然后在函数中       作为变量参与函数执行
默认参数:必须放在最后
    def show(a1,a2,a3 = 5):
        print(a1,a2,a3)
    show("wu","ha")
    #返回结果:wu ha 5

指定参数:
    def show(a1,a2):
        print(a1,a2)
    show(a2=52,a1=8)
    #返回结果:8 52

动态参数:
    *arg --序列:自动转换成一个元组
        def show(*arg):
            print(arg,type(arg))
        show(23,45,67)
        #返回结果:(23, 45, 67) <class 'tuple'>
        #or
        l = [23,45,67]
        show(*l)
        #返回结果:(23, 45, 67) <class 'tuple'>

    **arg --字典:自动转换成一个字典
        #默认字典处理
        def show(**arg):
            print(arg,type(arg))
        show(name1='swht',name2='shen')
        #返回结果:{'name1': 'swht', 'name2': 'shen'} <class 'dict'>
        #or
        d = {"name1"="swht","name2"="shen"}
        show(**d)
        #返回结果:{'name1': 'swht', 'name2': 'shen'} <class 'dict'>

    *arg,**kwarges --序列和字典
        def show(*args,**kwargs):
            print(args,type(args),'\n',kwargs,type(kwargs))
        show(23,45,67,82,name1='swht',name2='shen')
        #返回结果:(23, 45, 67, 82) <class 'tuple'> 
                   {'name2': 'shen', 'name1': 'swht'} <class 'dict'>        
        注意:使用*arg,**kwarges组合参数,必须是*arg在前,**kwarges在后,否则系统报错;另外实参在输入的时候也应该是按照上述顺序。

拓展:

def show(*args,**kwargs):
    print(args,type(args),'\n',kwargs,type(kwargs))
l = [23,45,67,82]
d = {'name1':'swht','name2':'shen'}
show(l,d)
#返回结果:
([23, 45, 67, 82], {'name1': 'swht', 'name2': 'shen'}) <class 'tuple'> 
{} <class 'dict'>

def show(*args,**kwargs):
    print(args,type(args),'\n',kwargs,type(kwargs))
l = [23,45,67,82]
d = {'name1':'swht','name2':'shen'}
show(*l,**d)
#返回结果:
(23, 45, 67, 82) <class 'tuple'> 
{'name2': 'shen', 'name1': 'swht'} <class 'dict'>

总结:
    函数可以传递元组、列表、字典等类型的值,由于带'*'、'**'的参数允许传入多个参数,所以在调用函数的时候默认将传入的参数识别到第一个*args。为了指定将参数传给某个args,这里需要对实参进行加'*'进行标识。

#list
show = "Welcome to {0},there have too many {1}!"
# reault = show.format("China","Foods")
l = ["China","Foods"]
reault = show.format(*l)
print(reault)
#返回结果:Welcome to China,there have too many Foods!

#dict
show = "{name} is a {acter}!"
# reault = show.format(name='swht',acter='teacher')
d = {'name':'swht','acter':'teacher'}
reault = show.format(**d)
print(reault)
#返回结果:swht is a teacher!

lambda表达式

    功能:简单函数的表示方式
    func = lambda a:a+1
    函数名  关键字 形参:函数体
    创建形式参数a,函数内容为a+1,并将结果return
测试代码:
    f = lambda x:x + 1
    ret = f(4)
    print(ret)

内置函数

abs()

功能:取绝对值
>>> abs(5)
5
>>> abs(-85)
85

all(iterable)

功能:iterable所有的元素都为真,返回True,否则返回False
备注:为False的元素:0、''、False或者空,其他的为True
参数:iterable为可迭代对象
all的功能可以使用下面的函数进行理解:
    def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
测试代码:
    all('test,hh')
    返回值为:True
    >>> all(['a', 'b', 'c', 'd'])  #列表list,元素都不为空或0
    True
    >>> all(['a', 'b', '', 'd'])  #列表list,存在一个为空的元素
    False
    >>> all([0, 1,2, 3])  #列表list,存在一个为0的元素
    False              
    >>> all(('a', 'b', 'c', 'd'))  #元组tuple,元素都不为空或0
    True
    >>> all(('a', 'b', '', 'd'))  #元组tuple,存在一个为空的元素
    False
    >>> all((0, 1,2, 3))  #元组tuple,存在一个为0的元素
    False
    >>> all([]) # 空列表
    True
    >>> all(()) # 空元组
    True    

any(iterable)

功能:iterable中元素只要有一个元素为真,则返回True,否则返回False(即iterable中所有的元素为假才会返回False)
参数:iterable为可迭代对象
any的功能可以使用下面的函数进行理解:
def any(iterable):
   for element in iterable:
       if  element:
           return False
   return True
测试代码:
    >>> any([0,1,2,3]) #列表中仅有一个元素0为假,返回True
    True
    >>> any([' ', '  ', '', 0])
    True
    >>> any([0]) #列表中元素只有一个元素0,返回False
    False
    >>> any([0,''])
    False
    >>> any([0,'',4])
    True    
    >>> any(('a', 'b', 'c', 'd'))  #元组tuple,元素都不为空或0
    True
    >>> any(('a', 'b', '', 'd'))  #元组tuple,存在一个为空的元素
    True
    >>> any((0, '', False))  #元组tuple,元素全为0,'',false
    False
    >>> any([]) # 空列表
    False
    >>> any(()) # 空元组
    False

map(iterable)

功能:对可迭代函数'iterable'中的每一个元素应用‘function’方法,将结果作为list返回
参考链接:http://segmentfault.com/a/1190000000322433
测试代码:
    def add_100(num):
        return num + 100
    li1 = [25,26,27]
    ret = list(map(add_100,li1))
    print(ret)
    返回结果:[125, 126, 127]


python2.7                                python3.5
两个版本的对比,真是让人感到诧异,python3上执行map明明已经获取了值,但非得加个list进行展示,超乎寻常。

def abc(a,b,c):
    return a*1000 + b*100 + c*10

list1 = [11,22,33]
list2 = [44,55,66]
list3 = [77,88,99]
ret = list(map(abc,list1,list2,list3))
print(ret) #返回结果 [16170, 28380, 40590]

ascii(object)

功能:该函数与python2中的repr()函数一样,返回一个可打印的对象字符串。当遇到非ascii码时,就会输出\x,\u或\U等字符来表示。例如:ascii(4) = int.__repr__(4) = repr(4)等号两边的方式是对等的。
测试代码:
    >>> ascii(54)
    '54'
    >>> ascii('o')
    "'o'"
    >>> type(ascii(54))
    <class 'str'>    
    >>> print(ascii(10), ascii(9000000), ascii('b\31'), ascii('0x\1000'))
        10 9000000 'b\x19' '0x@0'

bin()

功能:将整数转换为二进制字符串
>>> bin(56)
'0b111000'
>>> bin(100)
'0b1100100'
注意:如果bin()函数的实际参数不是一个整数,则该该实参(由类创建的对象)返回值必须是整数型
如:
>>> class myType:
...     def __index__(self):
...             return 56
...
>>> myvar = myType()
>>> bin(myvar)
'0b111000'

bool()

功能:获取对象的bool值
bool(0) #False
bool(5) #True
bool('') #False
#为假的元素:0 none 空列表 空字典 空元组 空字符串

bytearray()

功能:转成字符字典。Bytearray类型是一个可变的序列,并且序列中的元素的取值范围为 [0 ,255]。
>>> a = bytearray([5,8])
>>> a[0]
5
>>> a[1]
8
>>> a
bytearray(b'\x05\x08')

bytes()

    功能:返回一个新的数组对象,这个数组不能对数组元素进行修改,每个元素的取值范围为[0 ,255]
    测试代码:
    bytes(iterable_of_ints) 
        >>> b = bytes((5,8,6,8))
        >>> print(b)
        b'\x05\x08\x06\x08'
    bytes(string, encoding[, errors])     
        >>> bytes('sdjsd',encoding='utf-8')
        b'sdjsd'
    bytes(bytes_or_buffer)  ?
    bytes(int) 
        >>> bytes(5)
        b'\x00\x00\x00\x00\x00'
    bytes()  
        >>> bytes()
        b''

总结:(参考:http://blog.csdn.net/caimouse/article/details/40860827)
    bytes函数与bytearray函数主要区别是bytes函数产生的对象的元素不能修改,而bytearray函数产生的对象的元素可以修改。因此,除了可修改的对象函数跟bytearray函数不一样之外,其它使用方法全部是相同的。最后它的参数定义方式也与bytearray函数是一样的。

callable()

功能:判断函数或者对象是否可执行
>>> callable(5)
False
>>> callable(0)
False
>>> callable('')
False
>>> callable(int())
False
>>> callable(lambda x:x+1)
True

chr()

功能:参数为一个整型数字,返回值对应ASCII码的字符
>>> chr(5)
'\x05'
>>> chr(115)
's'
>>> chr(56)
'8'

ord()

功能:返回一个字符的ASCII码值
>>> ord('s')
115
>>> ord('5')
53

classmethod()

功能:classmethod是用来指定一个类的方法为类方法,没有此参数指定的类的方法为实例方法
    >>> class C: #定义一个类
    ...     @classmethod  #声明为类方法,不经过实例化就可以直接调用
    ...     def f(self): #定义一个函数(类的方法)
    ...             print "This is a class method"
    ...
    >>> C.f()  #通过类调用函数
    This is a class method
    >>> c = C()
    >>> c.f()
    This is a class method
    >>> class D:
    ...     def f(self):
    ...             print " This is not a class method "
    ...
    >>> D.f()  #没有经过@classmethod 声明的类方法,必须经过实例化才能被调用
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unbound method f() must be called with D instance as first argument (got nothing instead)
    >>> d = D()
    >>> d.f()
    This is not a class method

staticmethod()

    功能:类的静态方法,只能在类内部使用。经过静态类方法声明的类,在调用的时候不需要进行实例化

总结:对比classmethod()和staticmethod()

    静态方法:@staticmethod()
        class Foo(object):
            str = "I'm a static method."
            def bar():
                print(Foo.str)
            bar = staticmethod(bar)

        Foo.bar()
    返回结果:I'm a static method. 

    类方法:@classmethod()
        class Foo(object):
            str = "I'm a static method."
            def bar(cls):
                print(cls.str)
            bar = classmethod(bar)
        Foo.bar()
    返回结果:I'm a static method. 
较简单的操作代码:

    静态方法:@staticmethod()
        class Foo:
            str = "I'm a static method."
            @staticmethod
            def bar():
                print(Foo.str)
        Foo.bar() 
    返回结果:I'm a static method. 

    类方法:@classmethod()
        class Foo:
            str = "I'm a static method."
            @classmethod
            def bar(cls):
                print(cls.str )
        Foo.bar()
    返回结果:I'm a static method.

compile()、eval()、exec()

功能:compile语句是从type类型中将str里面的语句创建成代码对象。
    compile语句的目的是提供一次性的字节码编译,就不用在以后的每次调用中重新进行编译了
语法:compile( str, file, type )
    eveal_code = compile('1+2','','eval')
    >>>eveal_code
    返回结果:<code object <module> at 0x01555D40, file "", line 1>
    >>>eval(eveal_code)
    返回结果:3

    single_code = compile( 'print("apicloud.com")', '', 'single' )
    >>> single_code
    返回结果:<code object <module> at 0x01555B10, file "", line 1>
    >>> exec(single_code)
    返回结果:apicloud.com

complex()

功能:创建一个值为real + imag * j的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。
参数real: int, long, float或字符串;
参数imag: int, long, float
>>>complex()
0j
#数字
>>> complex(1,2)
(1+2j)
#当做字符串处理
>>> complex('1')
(1+0j)
#注意:这个地方在“+”号两边不能有空格,也就是不能写成"1 + 2j",应该是"1+2j",否则会报错
>>> complex('1+2j')
(1+2j)

delattr()

参考链接:http://www.cnblogs.com/zhangjing0502/archive/2012/05/16/2503702.html
功能:删除object对象名为name的属性
语法:delattr(object,name) 
参数object:对象。
参数name:属性名称字符串。

>>> class Person:
...     def __init__(self, name, age):
...             self.name = name
...             self.age = age
...
>>> tom = Person("Tom", 35)
>>> dir(tom)
['__doc__', '__init__', '__module__', 'age', 'name']
>>> delattr(tom, "age")
>>> dir(tom)
['__doc__', '__init__', '__module__', 'name']

getattr()

功能:用于返回一个对象属性,或者方法
class A:   
    def __init__(self):   
        self.name = 'zhangjing'  
    #self.age='24'
    def method(self):   
        print("method print")  

Instance = A()   
print(getattr(Instance , 'name', 'not find')) #如果Instance 对象中有属性name则打印self.name的值,否则打印'not find'
print(getattr(Instance , 'age', 'not find'))  #如果Instance 对象中有属性age则打印self.age的值,否则打印'not find'
print(getattr(a, 'method', 'default'))  
#如果有方法method,否则打印其地址,否则打印default   
print(getattr(a, 'method', 'default')()) 
#如果有方法method,运行函数并打印None否则打印default

li=["swht","shen"]
getattr(li,"pop")
返回结果:<built-in method pop of list object at 0x01AFDA80>

setattr()

功能:参数是一个对象,一个字符串和一个任意值。字符串可能会列出一个现有的属性或一个新的属性。这个函数将值赋给属性的。该对象允许它提供。
语法:setattr(object, name, value)    
setattr(x,“foobar”,123)相当于x.foobar = 123

hasattr()

功能:用于确定一个对象是否具有某个属性
语法:hasattr(object, name) -> bool
    判断object中是否有name属性,返回一个布尔值
li=["swht","shen"]
hasattr(li,'append')
返回结果:True

dict()

功能:字典定义函数,可以创建一个字典,也可以将其他类型(列表、元组、字符串)转换成字典类型
定义:
    dict1 = dict(one = 1, two = 2, a = 3)
    prin(dict1)
    {'one': 1, 'a': 3, 'two': 2}
类型转换:
    list1 = ['name','age',]
    list2 = ['swht',18]
    dict(zip(list1,list2))
    返回结果:{'name': 'swht', 'age': 18}

    new_list= [['key1','value1'],['key2','value2'],['key3','value3']]
    dict(new_list)
    返回结果:{'key3': 'value3', 'key1': 'value1', 'key2': 'value2'}

dir()

功能:查看函数或模块内的操作方法都有什么,输出的是方法列表。
如dir(int)可以直接获取int的所有方法,返回的类型是一个列表

divmod()

功能:divmod(a,b)方法返回的是a//b(除法取整)以及a对b的余数
>>> divmod(2,5)
(0, 2)
>>> divmod(12,5)
(2, 2)

enumerate()

功能:获取字典的索引值并指定开始值
li = ['swht','shen','test']
for i,k in enumerate(li,3): #遍历列表,索引值从3开始
    print(i,k)
#返回结果
3 swht
4 shen
5 test

filter()

参考链接:http://www.cnblogs.com/fangshenghui/p/3445469.html
功能:filter(function, sequence)对于队列中的item依次被function处理
def fun(item):
    if item != 4:
        return item
list1 = [5,4,8]
print(list(filter(fun,list1)))
返回结果:[4, 8]
总结:相当于一个过滤函数

frozenset()

参考:http://blog.csdn.net/caimouse/article/details/42042051
功能:本函数是返回一个冻结的集合
l = [1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 9]  
print(len(l), l)  
set = frozenset(l)  
print(len(set), set) 
返回结果:11 [1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 9]
         9 frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9})
总结:所谓冻结就是这个集合不能再添加或删除任何集合里的元素。因此与集合set的区别,就是set是可以添加或删除元素,而frozenset不行。frozenset的主要作用就是速度快,它是使用hash算法实现。参数iterable是表示可迭代的对象,比如列表、字典、元组等等

locals()、globals()

功能:基于字典的访问局部和全局变量的方式
locals 是只读的,globals 不是
关于名字空间的相关说明请移步参考:http://blog.csdn.net/scelong/article/details/6977867

hash()

功能:输出对象的hash值
>>> hash(8)
8
>>> hash('sd')
-584109415
>>> hash('99')
-1356598271
>>> hash('asds')
-1179125483

help()

功能:查看函数或模块用途的详细说明
使用方法:help(object)

类型转换

int(x [,base ])         将x转换为一个整数    
long(x [,base ])        将x转换为一个长整数    
float(x )               将x转换到一个浮点数    
complex(real [,imag ])  创建一个复数    
str(x )                 将对象 x 转换为字符串    
repr(x )                将对象 x 转换为表达式字符串    
eval(str )              用来计算在字符串中的有效Python表达式,并返回一个对象    
tuple(s )               将序列 s 转换为一个元组    
list(s )                将序列 s 转换为一个列表    
chr(x )                 将一个整数转换为一个字符    
unichr(x )              将一个整数转换为Unicode字符    
ord(x )                 将一个字符转换为它的整数值    
hex(x )                 将一个整数转换为一个十六进制字符串    
oct(x )                 将一个整数转换为一个八进制字符串

id()

功能:获取对象的内存地址
id(object)

input()

功能:获取用户的输入信息
input("请输入你的名字:")
>>>请输入你的名字:swht
swht

isinstance()

功能:判断对象类型
isinstance(5,int)
返回结果:True

issubclass()

功能:本函数用来判断类参数class是否是类型参数classinfo的子类
class Line:  
    pass  
class RedLine(Line):  
    pass  

class Rect:  
    pass  

print(issubclass(RedLine, Line))  #返回True  Redline是Line的子类
print(issubclass(Rect, Line))  #返回False  

iter()

功能:创建一个迭代器
for i in iter((1,2,4,5,6,7,)):
    print(i)
返回结果:1 2 4 5 6 7 #循环遍历元组

len()

功能:获取字符串的长度
len(str)

max()

功能:返回所有整数中最大的一个数
max(5,6,8,7) 
返回结果:8

memoryview()

功能:本函数是返回对象obj的内存查看对象
>>> v = memoryview(b'abc123')
>>> print(v[1])
98
>>> print(v[0])
97
>>> print(v[2])
import struct  
buf = struct.pack("i"*12, *list(range(12)))  
x = memoryview(buf)  
y = x.cast('i', shape=[2,2,3])  
print(y.tolist()) 
返回结果:[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]

总结:所谓内存查看对象,就是对象符合缓冲区协议的对象,为了给别的代码使用缓冲区里的数据,而不必拷贝,就可以直接使用。参考链接:http://blog.csdn.net/caimouse/article/details/43083627

sorted()

功能:排序
sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]

sum()

功能:返回整数数字的和
sum([1,5,8]) #参数是一个list
返回结果:14

super()

功能:用来解决多重继承问题

type()

功能:获取对象的类型
type(object)

vars()

功能:本函数是实现返回对象object的属性和属性值的字典对象
>>> class Foo:
...     a = 1
...
>>> print(vars(Foo))
{'a': 1, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__doc__': None, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__module__': '__main__'}

总结:如果默认不输入参数,就打印当前调用位置的属性和属性值,相当于locals()的功能。如果有参数输入,就只打印这个参数相应的属性和属性值。参考:http://blog.csdn.net/caimouse/article/details/46489079

zip()

功能:zip函数接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表
>>> x = [1,2,3,]
>>> y = [4,5,6,]
>>> z = [7,8,9,]
>>> xyz = zip(x,y,z)
>>> print(xyz)
<zip object at 0x00FBD968>
>>> print(list(xyz))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

random

功能:产生随机数
import random
random.randint(1,99) #从1-99中产生随机数

import()

功能:查看模块所在的位置
 __import__('random') #参数为一个字符串
<module 'random' from 'D:\\Program Files\\Python\\Python35\\python35.zip\\random.pyc'>

open()函数

博客参考:http://www.cnblogs.com/songqingbo/p/5102618.html

read()

功能:读取文件中的所有内容,返回的类型是字节

readline()

功能:读取文件中的一行数据。返回的类型是字节

readlines()

功能:读取文件中的所有内容,返回的类型是list

tell()

功能:查看当前指针位置,返回值类型为整数

seek()

功能:指定当前指针位置


files = open('test.txt','r',encoding='utf-8')
files.seek(5)
print(files.read()) #读取指为直接切割针5后面的所有字符
files.truncate() #获取指针5之前的所有字符然后写到原来的文件(或者可以理解)
files.close()

扩展

读二进制文件:

    input = open('data','rb')

读取所有内容:

    f = open('test.txt','r')
    try:
        all_txt_view = f.read()
    finally:
        f.close()

读取固定字节:

    f = open('test.txt','rb')
    try:
        while True:
            chunk = f.read(100)
            if not chunk:
                break
            pass
    finally:
        f.close()

读每行:

    list_of_all_the_lines = f.readlines()

如果文件是文本文件,还可以直接遍历文件对象获取每行:

    for line in f:
        print(line)

写文件写文本文件

    output = open('data','w')

写入多行:

    f.writeline(list_of_text_string)

作业:

作业连接:http://www.cnblogs.com/wupeiqi/articles/4950799.html
1. 用户输入一个字符串,将其转换成字典 使用json
2. 增加一条记录
3. (可选)删除一条
4. (可选)线上文件修改


global       
        log 127.0.0.1 local2
        daemon
        maxconn 256
        log 127.0.0.1 local2 info
defaults
        log global
        mode http
        timeout connect 5000ms
        timeout client 50000ms
        timeout server 50000ms
        option  dontlognull

listen stats :8888
        stats enable
        stats uri       /admin
        stats auth      admin:1234

frontend oldboy.org
        bind 0.0.0.0:80
        option httplog
        option httpclose
        option  forwardfor
        log global
        acl www hdr_reg(host) -i www.oldboy.org
        use_backend www.oldboy.org if www

backend test.oldboy.org
        server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
        #server 100.1.7.9 100.1.7.999 weight 20 maxconn 3000


backend buy.oldboy.org
        server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000

字典:        
{"backend": "test.oldboy.org",
 "record":{
        "server": "100.1.7.999",
        "weight": 20,
        "maxconn": 30
  }
}

python自动化开发 day02

Author:@南非波波

作者注:

经过第一天的学习以及后续的代码练习,给自己一个约定的代码风格、格式:
1. 模块名:
    模块应该使用尽可能短的、全小写命名,可以在模块命名时使用下划线以增强可读性。
    例如:
        login_shop.py
2. 类名定义:
    由于类名要求首字母必须大写,所以这样定义:
    class MyFristClass:  # 类名有三个单词组成,分别首字母大写
        def __init__(self,a):
            pass
3. 函数名定义:
    普通函数:
        选择使用字母小写,单词直接使用下划线_分割:
            shop_mag(users):
                pass
4. 变量名定义:
    全局变量名:
        字母全大写: SHOPLIST
    普通变量名:
        字母小写,单词分割选择使用首字母大写: shopUsers

以上规范并不是必须,但是作为个人的编程习惯而言,是一种很好的养成约束。

课程大纲地址: http://www.cnblogs.com/wupeiqi/articles/5115190.html

python知识拾忆:

Python2.x与Python3.x关于dict.keys()返回值的类型对比:

一、python种类

关于Python的一些版本内部执行的一些原理。从原理上来看待执行快慢的类型,从而选择自己需要的去学习。目前而言,最火的就是cpython了,这也是官方版本的Python。后面出现的pypy渐渐崭露头角,用银角大王的话讲:这货日后指定会火…

1. cpython  使用c解释器生产.pyc(字节码),然后转换成机器码,最后到cpu
2. javapython java解释器-->字节码-->机器码-->cpu
3. IronPython C#解释器-->字节码 --> 机器码--> cpu
4. pypy  内部使用自己的解释器编译成字节码-->机器码.最后在外部执行的时候直接是机器码,速度要快

银角大王推荐阅读书:《python源码剖析》

二、字节码

在Python内部字节码直接的转换过程如图:

python中进行字节码之间的转换流程大概是这样的:字节码类型转换从utf-8转换成gbk类型,首先需要执行解码变成Unicode类型,然后再由Unicode类型编码成gbk类型。[图片来源:银角大王课堂笔记]

三、字符串

博客链接:http://www.cnblogs.com/songqingbo/p/5126957.html

字符串的常用操作包括但不限于以下操作:

字符串的替换、删除、截取、复制、连接、比较、查找、分割等

这里将对字符串的内置操作方法进行总结归纳,重点是以示例的方式进行展示。

使用type获取创建对象的类 type(name)
使用dir获取类的成员dir(name)
使用vars获取类的成员和各个成员的值

capitalize

功能:字符串首字母大写
name = 'swhthaitun'
name.capitalize()
返回结果:'Swht'

casefold()首字母小写

name = 'HelloWord'
reault = name.casefold()
print(reault)
返回结果:helloword

casefold

功能:将字符串中所有的大写字母转换成小写字母
s1 = "['bsondump', 'mongo', 'mongod', 'mongodump', 'mongoexport', 'mongofiles', 'mongoimport', 'mongooplog', 'mongoperf', 'mongoLLKJKKore', 'mongos', 'UUUngostat', 'monGGtop']"
s1.casefold()
返回结果:"['bsondump', 'mongo', 'mongod', 'mongodump', 'mongoexport', 'mongofiles', 'mongoimport', 'mongooplog', 'mongoperf', 'mongollkjkkore', 'mongos', 'uuungostat', 'monggtop']"

center

功能:字符串宽度填充,使用原有字符串+填充字符构成指定长度的新的字符串
name = 'swhthaitun'
name.center(15)
返回结果:'   swhthaitun  ' #默认以空格进行填充
name.center(16,'*')
返回结果:'***swhthaitun***'

功能:字符串居中,以‘*’分割(20为新产生字符串的总的宽度)
name = 'HelloWord'
reault = name.center(20,'*')
print(reault)
返回结果:*****HelloWord******

count

功能:统计某个字符在字符串中出现的次数,或在字符串指定区间内完成上述操作
name = 'swhthaitun'
name.count('h')
返回结果:2
name.count('h',0,3)  #从索引值0-3范围的字符中统计'h'出现的次数
返回结果:1

功能:统计子序列出现的次数
name = 'HelloWord'
reault = name.count('W') #如果换成'w',返回结果为0,python对大小写敏感
print(reault)
返回结果:1

name = 'HelloWord'
reault = name.count('l',0,3) #统计单个字符出现的次数,可以指定起始范围,另外在python中起始范围讲究顾头不顾尾的原则,即[0,3)
print(reault)

encode

功能:对字符串进行编码操作
name = 'swhthaitun'
name.encode()
返回结果:b'swhthaitun'

功能:转变字符串的编码
name = '南非波波'
reault = name.encode('gbk')
print(reault)
返回结果:b'\xc4\xcf\xb7\xc7\xb2\xa8\xb2\xa8'

endswith

功能:判断字符串是否以某个字符串结尾的,返回值为bool型
name = 'swhthaitun'
name.endswith('s')
返回结果:False
name.endswith('n')
返回结果:True
name.endswith('tun')
返回结果:True

name = 'Iamalatterboy'
reault = name.endswith('y')
print(reault)
返回结果:True

expandtabs

功能:将制表符'\t'转换成指定宽度的tab键分割,默认tabsize=8
li = 'sw\tht'
li.expandtabs(4)
返回结果:'sw  ht'
li.expandtabs()
返回结果:'sw      ht'

find

功能:在字符串中查找指定字符串,找不到时返回-1
name = 'swht'
name.find('s')
返回结果:0
name.find('h')
返回结果:2

format

功能:格式化输出字符串
li = 'I\'m {},{}' #两个'{}'是占位符
li.format('swht','欢迎来中国')
返回结果:"I'm swht,欢迎来中国"
参考:http://blog.chinaunix.net/uid-23802873-id-4477364.html

__contains__

功能:包含 -->'eal' in name
name = 'swhtkkskjj'
reault = name.__contains__('swht')
print(reault)
返回结果:True

index

功能:在字符串中查找指定的字符串,找不到时直接报错
name = 'swhthaitun'
name.index('w')
返回结果:1    

join()

功能:字符串连接
name = 'swhthaitun'
'*'.join(name)
返回结果:'s*w*h*t*h*a*i*t*u*n'

isalnum

功能:检查判断字符串是否包含字母数字字符(http://www.yiibai.com/python/string_isalnum.html)
name = 'swhthaitun'
name.isalnum()
返回结果:True

isalpha

功能:检测字符串是否只由字母组成(http://www.runoob.com/python/att-string-isalpha.html)
name = 'swhthaitun'
name.isalpha()
返回结果:True

isdecimal

功能:检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。(参考:http://www.runoob.com/python/att-string-isdecimal.html)
name = 'swhthaitun'
name.isdecimal()
返回结果:False

isdigit

功能:检测字符串是否只由数字组成。(参考:http://www.runoob.com/python/att-string-isdigit.html)
name = 'swhthaitun'
name.isdigit()
返回结果:False

isidentifier

功能:检测字符串是否是字母开头
name = 'swhthaitun'
name.isidentifier()
返回结果:True
name = '1swhthaitun'
name.isidentifier()
返回结果:False

isnumeric

功能:检测字符串是否只由数字组成。这种方法是只针对unicode对象。
name = 'swhthaitun'
name.isnumeric()
返回结果:False
Li = '5523'
Li.isnumeric()
返回结果:True

isprintable

功能:判断字符串中所有字符是否都属于可见字符
a = "\tPuppy"
a.isprintable()
返回结果:False
name = 'swhthaitun'
name.isprintable()
返回结果:True

isspace

功能:检测字符串是否为空格
name = 'swhthaitun'
name.isspace()
返回结果:False
Li = ' '
Li.isspace()
返回结果:True

istitle

功能:判断字符串是否适合当作标题(其实就是每个单词首字母大写)
a = "a puppy"
b = "Puppy"
a.istitle()
返回结果:False
b.istitle()
返回结果:True

isupper

功能:判断字符串中所有字母字符是否都是大写字母
a = "puppy"
b = "PUPPY"
a.isupper()
返回结果:False
b.isupper()
返回结果:True

ljust

功能:返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。(参考:http://www.runoob.com/python/att-string-ljust.html)
语法:str.ljust(width[, fillchar])
     width -- 指定字符串长度。
     fillchar -- 填充字符,默认为空格。
name = 'swhthaitun'
name.ljust(50,'*')
返回结果:'swhthaitun****************************************'

lower

功能:将所有的字母转换成小写字母
name = 'SWHT'
name.lower()
返回结果:'swht'

lstrip

功能:去除字符串左边开头的空格
name = '  swht   '
name.lstrip()
返回结果:'swht   '

rstrip

功能:去除字符串右边结尾的空格
name = '  swht   '
name.rstrip()
返回结果:'   swht'

strip

功能:去除字符串两边的空格
name = '  swht   '
name.rstrip()
返回结果:'swht'

maketrans

功能:用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
注:两个字符串的长度必须相同,为一一对应的关系。
语法:str.maketrans(intab, outtab)
参数:intab -- 字符串中要替代的字符组成的字符串。
      outtab -- 相应的映射字符的字符串。
intab = "swhtr"
outtab = "12345"
name = "hjjksknsnjmk"
name.maketrans(intab, outtab)
返回结果:{104: 51, 114: 53, 115: 49, 116: 52, 119: 50}

partition

功能:根据指定的分隔符将字符串进行分割。
    如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。
name = 'swht'
li = 'hhsslswhtolljm'
li.partition(name)
返回结果:('hhssl', 'swht', 'olljm')

replace

功能:把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
语法:str.replace(old, new[, max])
参数:old -- 将被替换的子字符串。
     new -- 新字符串,用于替换old子字符串。
     max -- 可选字符串, 替换不超过 max 次
str = "this is string example....wow!!! this is really string"
str.replace("is", "was")
返回结果:'thwas was string example....wow!!! thwas was really string'
str.replace("is", "was", 3)
返回结果:'thwas was string example....wow!!! thwas is really string'

split

功能:字符串分割,默认是空格
name.split()
返回结果:['swht']
name.split('s') #以's'字符进行分割
返回结果:['', 'wht']

__add__

功能:在字符串后面增加指定的字符或字符串
name = 'swht'
name.__add__('e')
返回结果:'swhte'
li = 'hjh'
name.__add__(li)
返回结果:'swhthjh'

__contains__

功能:判断指定字符串是否包含在字符串中,返回值为True和False
name = 'swht'
name.__contains__('s')
返回结果:True

__eq__

功能:判断字符串是否相等,返回值为True和False
name = 'swht'
li = 'test'
name.__eq__(li)
返回结果:False        

splitlines

功能:按照行分隔,返回一个包含各行作为元素的列表,如果 num 指定则仅切片 num 个行.
语法:str.splitlines( num=string.count('\n'))
参数:num -- 分割行的次数
Li = "Line1-a b c d e f\nLine2- a b c\n\nLine4- a b c d"
Li.splitlines(0)
返回结果:['Line1-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d']
Li.splitlines(1)
返回结果:['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']

startswith

功能:判断一个字符串是否以某个或几个字符开始,结果以True或者False返回。
name = "swhtlllds"
name.startswith('s')
返回结果:True

endswith

功能:判断一个字符串是否以某个或几个字符结束,结果以True或者False返回。
name = "swhtlllds"
name.endswith('ds')
返回结果:True

swapcase

功能:用于对字符串的大小写字母进行转换。
name = 'swht'
name.swapcase()
返回结果:'SWHT'
name = 'Swht'
name.swapcase()
返回结果:'sWHT'

upper

功能:将字符串中的小写字母转为大写字母
name = 'swht'
name.swapcase()
返回结果:'SWHT'

title

功能:进行标题转换,即单词首字母大写
name = 'swht ni li'
name.title()
返回结果: 'Swht Ni Li'

translate

功能:根据参数table给出的表(包含 256 个字符)转换字符串的字符, 要过滤掉的字符放到 del 参数中。
方法:str.translate(table[, deletechars]);
参数:table -- 翻译表,翻译表是通过maketrans方法转换而来。
     deletechars -- 字符串中要过滤的字符列表。
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

str = "this is string example....wow!!!";
print str.translate(trantab);
返回结果:th3s 3s str3ng 2x1mpl2....w4w!!!

zfill

功能:垫零左侧的字符串,以填补宽度
语法:str.zfill(width)
参数:width:最后的字符串宽度
str = "this is string example....wow!!!"        
print str.zfill(40)
print str.zfill(50)
返回结果:00000000this is string example....wow!!!
         000000000000000000this is string example....wow!!!

四、列表

博客链接:http://www.cnblogs.com/songqingbo/p/5126943.html

列表的基本操作示例展示:

append

功能:列表追加元素
name = ['sd','dfdf','drer']
name.append('sdsd')
返回结果:name
        ['sd', 'dfdf', 'drer', 'sdsd']

clear

功能:情况列表元素
name = ['sd','dfdf','drer']
name.clear()
返回结果:name
         []

copy

功能:浅拷贝,即只拷贝第一层的元素
name = ['sd','dfdf','drer']
li = ['ssd']
li = name.copy()
返回结果:li
         ['sd', 'dfdf', 'drer']

name = ['sd','dfdf','drer',['sddss','sdsdsd']]
li = ['ssd']
li = name.copy()
返回结果:li
['sd', 'dfdf', 'drer', ['sddss', 'sdsdsd']]

count

功能:统计列表指定元素个数
name = ['sd','dfdf','drer',['sddss','sdsdsd']]
name.count('sd')
返回结果:1
li = ['sd','sdsds',['sd','dffdg',],]
li.count('sd') #只统计第一层的元素个数
返回结果:1

extend

功能:追加字符元素或列表元素
name = ['sd','dfdf','drer',['sddss','sdsdsd']]
li = ['sd','sdsds',['sd','dffdg',],]
name.extend('ss')
返回结果:name
['sd', 'dfdf', 'drer', ['sddss', 'sdsdsd'], 's', 's']
name.extend('d')
返回结果:name
['sd', 'dfdf', 'drer', ['sddss', 'sdsdsd'], 's', 's', 'd']
name.extend(li)
返回结果:name
['sd', 'dfdf', 'drer', ['sddss', 'sdsdsd'], 's', 's', 'd', 'sd', 'sdsds', ['sd', 'dffdg']]

index

功能:定位列表中某元素
name = ['sd','dfdf','drer',['sddss','sdsdsd']]
name.index('sd')
返回结果:0
name.index('drer')
返回结果:2
返回结果:name.index('dr')  #当出现某元素不在列表中的时候会直接报错
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        ValueError: 'dr' is not in list

insert

功能:在指定索引位置的元素前面插入新的元素
name = ['sd','dfdf','drer',['sddss','sdsdsd']]
name.insert(3,'sd')
返回结果:name
['sd', 'dfdf', 'drer', 'sd', ['sddss', 'sdsdsd']]

pop

功能:删除指定索引值的元素,返回值为当前删除的元素的值。不指定索引值,默认删除最后一个元素
name = ['sd','dfdf','drer',['sddss','sdsdsd']]
name.pop(3)
返回结果:'sd'

remove

功能:删除列表中指定的元素
name = ['sd','dfdf','drer',['sddss','sdsdsd']]
name.remove('sd')
name
返回结果:['dfdf', 'drer', ['sddss', 'sdsdsd']]

reverse

功能:用于反向列表中元素。
name = ['sd','dfdf','drer',['sddss','sdsdsd']]
name.reverse()
name
返回结果:[['sddss', 'sdsdsd'], 'drer', 'dfdf', 'sd']

sort

功能:对单层列表进行元素的排序
name = ['sd','dfdf','drer',]
name.sort()
name
返回结果:['dfdf', 'drer', 'sd']

name = ['sd','dfdf','drer',['sddss','sdsdsd']]
name.sort() #报错的
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

五、元组

关于元组的常用操作,请参考:http://www.runoob.com/python/python-tuples.html

博客链接:http://www.cnblogs.com/songqingbo/p/5126947.html

元组的元素不可修改 ,元组的元素的元素可修改

count(self,value)

功能:统计当前元组中某元素的个数
tup = (55,77,85,55,96,99,22,55,)
tup.count(55)
返回结果:3 
备注:元素‘55’在元组tup中出现了3次

index(self, value, start=None, stop=None)

功能:获取元素在元组中的索引值,对于重复的元素,默认获取从左起第一个元素的索引值
tup = (55,77,85,55,96,99,22,55,)
tup.index(55)
返回结果:0
tup.index(85)
返回结果:2
tup.index(55,2,7)
返回结果:3

__add__

功能:将另一个元组追加到当前元组后面.__add__()只接收元组类型的序列
tup1 = (12,33,566,78,)
tup2 = (55,66,77,)
tup1.__add__(tup2)
返回结果:(12,33,566,78,55,66,77,)

__contains__

功能:包含,判断某元素是否包含在元组中
tup = (55,77,85,55,96,99,22,55,)
tup.__contains__(55)
返回结果:True  
备注:返回值类型是bool型,该方法判断在对成员元素是否存在元组中,程序根据返回不同的bool值进行相应的值返回或者操作

__eq__

功能:判断两个元组是否相等,返回值类型为bool型
tup = (55,77,85,55,96,99,22,55,)
tup1 = (55,77,85,55,96,99,22,551,)
tup.__eq__(tup1)
返回结果:False

__getattribute__

pass

__getitem__

功能:获取指定索引值的元素值
tup = (55,77,85,55,96,99,22,55,)
tup.__getitem__(5)
返回结果:99

__getnewargs__

功能:只是获取原来的元组??无卵用
tup = (55,77,85,55,96,99,22,55,)
tup.__getnewargs__()
返回结果:((55, 77, 85, 55, 96, 99, 22, 55),)

__ge__

功能:判断当前元组是否大于等于某个元组
tup = (55,77,85,55,96,99,22,55,)
tup1 = (55,77,85,55,96,99,22,551,)
tup.__ge__(tup1)
返回结果:False #bool类型

__gt__

功能:判断当前元组是否大于某个元组
tup = (55,77,85,55,96,99,22,55,)
tup1 = (55,77,85,55,96,99,22,551,)
tup.__ge__(tup1)
返回结果:False #bool类型

__hash__

功能:计算元组的hash值
tup = (55,77,85,55,96,99,22,55,)
tup1 = (55,77,85,55,96,99,22,551,)
tup.__hash__()
返回结果:-2123087613
tup1.__hash__()
返回结果:1338854611

__init__

功能:初始化作用,无返回值

__iter__

功能:获取元组的内存地址
tup = (55,77,85,55,96,99,22,55,)
tup1 = (55,77,85,55,96,99,22,551,)
tup.__iter__()
返回结果:<tuple_iterator object at 0x01C21F70>
tup1.__iter__()
返回结果:<tuple_iterator object at 0x01C21F50>

__len__

功能:获取元组的长度
tup.__len__()  #该方法已经被放到python的内置函数中,可以使用len(tup)获取长度
返回结果:8

__le__

功能:判断当前元组是否小于等于某个元组
tup = (55,77,85,55,96,99,22,55,)
tup1 = (55,77,85,55,96,99,22,551,)
tup.__le__(tup1)
返回结果:True #bool类型

__lt__

功能:判断当前元组是否小于某个元组
tup = (55,77,85,55,96,99,22,55,)
tup1 = (55,77,85,55,96,99,22,551,)
tup.__lt__(tup1)
返回结果:True #bool类型

__mul__

功能:把当前元组按照某个值的倍数进行元组的扩展,产生新的元组
tup = (55,77,85,55,96,99,22,55,)
tup.__mul__(2)
返回结果:(55, 77, 85, 55, 96, 99, 22, 55, 55, 77, 85, 55, 96, 99, 22, 55)
tup.__iter__()
返回结果:<tuple_iterator object at 0x01C21F70>
tup.__mul__(2).__iter__()
返回结果:<tuple_iterator object at 0x01C2F050>

__new__

pass

__ne__

功能:判断当前元组不等于某个元组
tup = (55,77,85,55,96,99,22,55,)
tup1 = (55,77,85,55,96,99,22,551,)
tup.__ne__(tup1)
返回结果:True #bool类型

__repr__

功能:将元组转换成一个字符串
tup = (55,77,85,55,96,99,22,55,)
tup.__repr__()
返回结果:'(55, 77, 85, 55, 96, 99, 22, 55)'
 type(tup.__repr__())
返回结果:<class 'str'>

__rmul__

功能:??怎么感觉跟__mul__一个德行??
tup = (55,77,85,55,96,99,22,55,)
tup.__rmul__(2)
返回结果:(55, 77, 85, 55, 96, 99, 22, 55, 55, 77, 85, 55, 96, 99, 22, 55)

六、字典

博客链接:http://www.cnblogs.com/songqingbo/p/5127044.html

字典的常用操作:

clear

功能:清空字典
dict_li = {'users':'swht','age':'18',}
dict_li.clear()
返回结果:dict_li
        {}

copy

功能:浅拷贝
dict_li = {'users':'swht','age':'18',}
dict_li.copy()
返回结果:{'age': '18', 'users': 'swht'}
dict_li = {'users':'swht','age':'18','address':{'sd':'dz'}}
dict_li.copy()
返回结果:{'age': '18', 'users': 'swht', 'address': {'sd': 'dz'}}

fromkeys()

功能:用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值。
语法:dict.fromkeys(seq[, value]))
参数:seq -- 字典键值列表。
     value -- 可选参数, 设置键序列(seq)的值。
li = ['users','age']
dict_li = dict.fromkeys(li,'swht')
返回结果:dict_li
        {'age': 'swht', 'users': 'swht'}

get

功能:获取字典的value值
dict_li = {'users':'swht','age':'18',}
dict_li.get('users')
返回结果:'swht'

items

功能:返回可遍历的(键, 值) 元组数组
dict_li = {'users':'swht','age':'18',}
dict_li.items()
返回结果:dict_items([('age', '18'), ('users', 'swht')])

keys

功能:获取字典可遍历的键
dict_li = {'users':'swht','age':'18',}
dict_li.keys()
返回结果:dict_keys(['age', 'users'])

pop

功能:删除字典中指定的键值
dict_li = {'users':'swht','age':'18',}
dict_li.pop('age')
返回结果:'18'

popitem

功能:随机返回并删除字典中的一对键和值
dict_li = {'users':'swht','age':'18',}
dict_li.popitem()
返回结果:('age', '18')
dict_li
{'users': 'swht'}

setdefault

功能:查找键值,如果键不已经存在于字典中,将会添加键并将值设为默认值。
dict_li = {'users':'swht','age':'18',}
dict_li.setdefault('ID',5)
返回结果:5
dict_li
返回结果:{'age': '18', 'users': 'swht', 'ID': 5}

update

功能:把指定字典的键值更新到当前字典中
dict_li = {'users':'swht','age':'18',}
dict_ai = {'address':'山东'}
dict_li.update(dict_ai)
dict_li
返回结果:{'age': '18', 'users': 'swht', 'address': '山东'}

values

功能:获取字典的所有值
dict_li = {'age': '18', 'users': 'swht', 'address': '山东'}
dict_li.values()
返回结果:dict_values(['18', 'swht', '山东'])

七、set集合

博客链接:http://www.cnblogs.com/songqingbo/p/5128066.html

set集合是一个无序且不重复的集合。
创建一个set集合:
    name = set('sdd')
    name
    返回结果:{'d', 's'}

add

功能:增加集合元素
name = {'d', 's'}
name.add('d')
name
返回结果:{'d', 's'}
name.add('sd')
name
返回结果:{'sd', 'd', 's'}

clear

功能:清空集合元素
name = {'d', 's'}
name.clear()
name
返回结果:{}

copy

功能:浅拷贝
name = {'sd', 'd', 's'}
li = name.copy()
返回结果:li
        {'sd', 'd', 's'}

difference

功能:取差集
name = {'sd', 'd', 's'}
li = set()
name.difference(li)
返回结果:name.difference()
{'sd', 'd', 's'}

difference_update

功能:删除当前set中的所有包含在 new set 里的元素
li = ('s', 'd')
name = {'sd', 'd', 's'}
name.difference_update(li)
name
返回结果:{'sd'}

discard

功能:移除元素
name = {'sd', 'd', 's'}
name.discard('s')
返回结果:name 
        {'sd', 'd'}

intersection

功能:取交集,建立新的set集合
li = ('s', 'd')
name = {'sd', 'd', 's'}
name.intersection(li)
返回结果:{'d', 's'}

intersection_update

功能:取交集,更新原来的set集合
li = ('s', 'd')
name = {'sd', 'd', 's'}
name.intersection_update(li)
返回结果:{'d', 's'}

isdisjoint

功能:判断没有交集,返回True,否则,返回False
li = {'s', 'd'}
name = {'sd', 'd', 's'}
name.isdisjoint(li)

issubset

功能:判断是否是子集
li = {'s', 'd'}
name = {'sd', 'd', 's'}
name.issubset(li)  #判断name是不是li的子集
返回结果:False
li.issubset(name)  #判断li是不是name的子集
返回结果:True

issuperset

功能:判断是否是父集
li = {'s', 'd'}
name = {'sd', 'd', 's'}
name.issuperset(li)  #判断name是不是li的父集
返回结果:True
li.issuperset(name)  #判断li是不是name的父集
返回结果:False

pop

功能:移除集合元素
name = {'sd', 'd', 's'}
name.pop()
返回结果:'sd' #随机删除集合元素
se1 = {'a','s','sb'}
se1.pop()
返回结果:'sb'

remove

功能:移除指定集合元素
name = {'sd','d','s'}
name.remove('s')
返回结果:name
{'sd', 'd'}

symmetric_difference

功能:去两个集合的差集,建立新的set集合对象
name = {'sd', 'd', 's'}
li = {'s', 'd'}
name.symmetric_difference(li)
返回结果:{'sd'}

symmetric_difference_update

功能:去两个集合的差集,更新原来的集合对象
name = {'sd', 'd', 's'}
li = {'s', 'd'}
name.symmetric_difference_update(li)
返回结果:{'sd'}

union

功能:并集,创建新的对象
name = {'sd', 'd', 's'}
li = {'s', 'd','h'}
name.union(li)
返回结果:{'h', 's', 'd', 'sd'}

update

功能:更新已有集合
name = {'sd', 'd', 's'}
name.update('df')
name
返回结果:{'sd', 'd', 'f', 's'}

八、类与对象

对象

python中一切事物皆对象,对象是一开始就有的,只是我们无法访问它。访问对象需要以变量的形式去访问(即创建变量指向到对象的,变量即对对象的引用)
在python中,一个对象的特征也称为属性(attribute)。它所具有的行为也称为方法(method)
结论:对象=属性+方法

在python中,把具有相同属性和方法的对象归为一个类(class)
比如人类,动物,植物等等,这些都是类的概念。 
类是对象的模板或蓝图,类是对象的抽象化,对象是类的实例化。类不代表具体的事物,而对象表示具体的事物。
类包含描述对象的方法。

int

取绝对值:
    age = -19
    age.__abs__() #int类函数调用
    abs(-19) #内置函数方式操作
取商和余数:
    age = 95
    age.__divmod__(10) #95/10 -->(9,5)
相加:
    a = 5,b=6
    a.__add__(b) #调用int的类函数add,相当于a + b  -->11
    a + b #内置函数方式操作

作业:

1. 博客整理
2. 购物商城实现
    1. 商品展示,价格
    2. 购物车添加商品(进行差异商品,同一种商品应该只存在一条数据)
    3. 付款(根据钱进行判断是否可以满足付款)
3. 预习
    http://www.cnblogs.com/wupeiqi/articles/5115190.html  后面的部分

python自动化开发 day01

Author:@南非波波

作者注:

  python学习旅程正式开启,这一天将是一个新的开始。希望我们在python开发的道路上多多积累、多分享!

一、python简介

python应用 
    Disgus Voitze Yelip Mozilla Quora  Redit
    豆瓣、知乎、sohu、腾讯、网易、金山、雅虎、Facebook、 Instagram(图片分享)
python2与python3比较
    经过多年的发展,python3已经得到更多的第三方优秀函数库兼容,对比python2来说,python3表现出来的精简高效特性让开发者们跃跃欲试。
    另外,python2.7.11作为python2版本的最后一个版本,不再有新版本推出,这样官方更多的引导开发者快速的向python3版本上进行转移。
    在本次学习的过程中,我们会穿插在python2和python3两个版本之间进行学习,后续的测试代码在开头会明确标记python的使用版本。相关注释都会对python2和python3的差异进行描述。

二、python安装

1.windows端安装
    安装包下载地址:
        python2.7版本:
            https://www.python.org/ftp/python/2.7.11/python-2.7.11.amd64.msi
        python3.5版本:
            https://www.python.org/ftp/python/3.5.1/python-3.5.1-amd64.exe  #安装版
            https://www.python.org/ftp/python/3.5.1/python-3.5.1-embed-win32.zip #免安装版
    安装步骤:
        使用可执行程序进行安装,按照流程进行安装即可,注意在安装的时候选择“安装路径”和一些必要的插件,比如pip、easy_install等
        使用免安装的文件(可嵌入的)进行环境配置:
        ![](http://i.imgur.com/U827QAb.jpg)
2.linux端安装
    centos6等常用系统自带的python版本为2.6,有特殊需求的朋友可能需要升级到python2.7或者python3版本。下面链接以python2.7.8为例进行编译安装。
        http://swht1278.blog.51cto.com/7138082/1728427
    提供一下python版本的下载地址:
        python2.7.11版本:
            https://www.python.org/ftp/python/2.7.11/Python-2.7.11.tgz
        python3.5版本:
            https://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz
3.Ubuntu端安装
    最新版本的Ubuntu系统(15.04等)已经自带了python2.7.9和python3.4.5两个版本的python环境,我们只需要在shell终端输入python2或python3进行调用即可。老版本的系统升级python环境需要以下操作:
        # 增加python源
        sudo add-apt-repository ppa:fkrull/deadsnakes
        # update 软件列表
        sudo apt-get update
        # 安装python3
        sudo apt-get install python3.5

三、基础概念

变量:Python 是动态类型语言, 也就是说不需要预先声明变量的类型。变量是对象的引用,变量只是将指针指向了对象所在的内存地址。变量的类型和值在赋值那一刻被初始化。
变量起名:
    1.显式-->通俗易懂
    2.nums_of_alex_gf = 19 
    3.NumsOfAlexGf = 20  驼峰写法
    4.中横线不能作为变量的命名字符
    5.数字不能作为开头,但可以在中间或者结尾
    6.特殊字符不能作为变量名的组成部分
    7.不能使用空格
    8.关键字不能声明为变量

四、运算符

算术运算符
    +  -  *  /   //  %  **
    /:传统除法,将执行地板除法,
    //:浮点除法,即去尾法除法,保留位数与除数和被除数的小数位数有关 (取整除,返回商的部分)
    **:平方运算
比较运算符
    <  <=  >  >=  ==  !=   <>
    不等于:!=   <>
    返回值是:True 和 False
赋值运算符
    >>> counter = 0 
    >>> miles = 1000.0 
    >>> name = 'Bob' 
    >>> counter = counter + 1 
    >>> kilometers = 1.609 * miles 
    >>> print '%f miles is the same as %f km' % (miles, kilometers)
    1000.000000 miles is the same as 1609.000000 km
    支持简写:n=n*3 -> n*=3  但不支持自增自减,因为“-” 和”+”是单目字符,--n -> -(-n)n
位运算符
    &      按位与      (a&b)
    |      按位或    (a|b)
    ^    按位异或    (a^b)
    ~    按位取反    (~a)
    <<    左移动     a<<1 整体向左移动,结果是原来数值的2倍
    >>  右移动    a>>1 整体向右移动,结果是原来数值的1/2
逻辑运算符
    and 布尔“与”     同真为True
    or  布尔“或”     同假为False
    not    布尔“非”     非True即False
成员运算符
    in     如果在指定序列中找到指定的值,返回True
    not in 如果在指定序列中没找到指定的值,返回False
身份运算符
    is  判断两个标识符是不是引用自同一个对象
        type(names) is list 判断某个变量值的类型(list、int、dic)
    is not 判断两个标识符是不是引用自不同对象

五、字符编码

python2 中在输入中文字符的时候会报字符编码的错误,在python3中已经引入了Unicode(万国码、统一码、),它为每种语言中的每个字符设定了统一并且唯一的二进制编码,规定所有的字符和符号最少由16位二进制来表示(2个字节),即2 ** 16 = 65536
UTF-8,是对Unicode编码的压缩和优化,它不再使用最少2个字节,而是将所有的字符和符号进行分类:ascii码中的内容用1个字节保存,欧洲的字符用2个字节保存,东亚的字符用3个字节保存

示例
python2
    #!/usr/local/env python2
    # -*- coding: utf-8 -*-  # 声明使用的字符类型,否则会报错
    '''
    @swht
    '''
    print "你好!"

python3
    #!/usr/local/env python3
    '''
    @swht
    '''
    print ("你好!")

总结:在python3中完全不用考虑字符编码的问题,python解释器会自行处理字符类型的问题

六、python流程控制

流程控制分为两大类:条件判断和循环
其中循环又分为两类:for循环和while循环
条件判断和循环可以单独存在,也可以嵌套使用,以处理更为复杂的逻辑问题。

下面会从if条件判断for循环while循环进行代码示例:

if_ex.py

#!/usr/bin/env python3
'''
@swht
'''
LuckyNum = 9
# 让用户输入一个数值与指定的值进行比较,当然这里没有处理用户输入为空的情况
# strip() 可以截取用户输入字符串首尾的空格
UserInputNum = int(input("请从1-100之间选择一个数字输入:").strip())
if UserInputNum > LuckyNum:
    print("你输入的数字比我的LuckNum要大哦!")
elif UserInputNum < LuckyNum:
    print("你输入的数字比我的LuckNum要小哦!")
else:
    print("恭喜你猜中了我的LuckNum,原来你就是我的幸运天使!")

while_ex.py

#!/usr/bin/env python3
'''
@swht
'''
LuckyNum = 9
# 设置一个标志位,用于程序判断退出循环,
flag = True
while flage:
UserInputNum = int(input("请从1-100之间选择一个数字输入:").strip())
if UserInputNum > LuckyNum:
    print("你输入的数字比我的LuckyNum要大哦!")
elif UserInputNum < LuckyNum:
    print("你输入的数字比我的LuckyNum要小哦!")
else:
    print("恭喜你猜中了我的LuckyNum,原来你就是我的幸运天使!")
    flag = False 

for_ex.py

#!/usr/bin/env python3
'''
@swht
'''
LuckyNum = 9
for count in range(3):
    UserInputNum = int(input("请从1-100之间选择一个数字输入:").strip())
    if UserInputNum > LuckyNum:
        print("你输入的数字比我的LuckyNum要大哦!")
    elif UserInputNum < LuckyNum:
        print("你输入的数字比我的LuckyNum要小哦!")
    else:
        print("恭喜你猜中了我的LuckyNum,原来你就是我的幸运天使!")
        break
else:
    print("你输入的次数已达到3次,程序即将退出!")

对比break和countnue

break是结束整个循环体,continue是结束单次循环

示例
    #!/usr/local/env python3
    '''
    @swht
    '''
    x = 0
    while x < 10:
        if x ==3:
            break
        x += 1
        print("x=%s" % x)
    输出结果:    x=1
                x=2
                x=3
    直接退出了整个while循环

七、格式化输出

使用'''string'''可以很方便的将多行内容进行注释,另外这个符号还有一个功能,那就是文档描述的功能。一般而言,在程序的前面后有一个文档说明,包括作者信息,版本信息,功能等

#!/usr/bin/env python
'''
@swht
'''

name = input("name:")
age = input("age:")
job = input("job:")

print("Information of:" + name + "\nname:" + name + "\nage:" + age + "\njob:" + job)
print("Information of %s\nname:%s\nage:%s\njob:%s" %(name,name,age,job))
print('''
    Infomation of %s
             name:%s
              age:%s
              job:%s
    ''' % (name,name,age,job))

八、数据类型:

列表转换成元组:tuple(name_list)

元组转换成列表:list(元组_name)

1.数字
    int     整型
    long     长整型
    float     浮点型
2.布尔
    1    真
    0    假
3.字符串
        stinglist = “Hello World”
    字符串操作:
        (参考:http://www.cnblogs.com/zhxiang/p/3385242.html
        http://www.jb51.net/article/47956.htm)
        移除空白:stinglist.strip()
        移除特殊字符:stinglist.lstrip().rstrip(',')
        分割:>>> stringlist[2]
                 'l'
        长度:>>> len(stringlist)
                 11
        索引:>>> stringlist.index('W') #字母‘W’所在的索引值
                 6
        切片:>>> stringlist[0:3] #顾前不顾尾
                 'Hel'
        字符串在输出时的对齐:
            >>> stringlist[0:3]
            'Hel'
            >>> stringlist[0:3].ljust(5) #ljust(width,[fillchar]) fillchar为填充字符,默认为空格
            'Hel  '
        字符串拼接:
            >>> stringlist += s
            >>> stringlist
            'Hello Worldab,cde,fgh,ijk'
        大小写转换:
            >>>stringlist.lower() #小写
               'hello world'
            >>> stringlist.upper() #大写
                'HELLO WORLD'
            >>> stringlist.swapcase() #大小写互换
                'hELLO wORLD'
            >>> stringlist.capitalize() #首字母大写
                'Hello world' 
            >>> string.capwords(stringlist) #以空格分割,每个单词首字母大写
                'Hello World'
        字符串翻转:
            >>> s
            'sdsds sdsdsff'
            >>> s = s[::-1]
            >>> s
            'ffsdsds sdsds'
        字符串查找:
            >>> stringlist.find('World')
                6
        判断是否为整型:
            >>> stringlist.isdigit()
                False
        判断字符串是否为空格:
            >>> stringlist.isspace()
                False
        转换成列表:
            >>> stringlist.split() #默认以空格为分割
                ['Hello', 'World']

4.列表(dir(name_list)获取列表操作帮助)
    参考:http://www.jb51.net/article/46768.htm
    name_list = ['alex', 'sddkd', 'shdjsjd', 'shen', 'swht', 'test']
    移除空白:name_list.strip()
    获取元素:name_list[index_num]
    索引:name_list.index("swht")  获取指定元素的索引值
    追加:name_list.append("test") 在列表后面追加一个元素
    插入:name_list.insert(3,"ssdd") 在索引值3后面插入新的元素
    删除:name_list.pop() 删除最后一个元素
         name_list.remove("test") 删除指定的元素
    排序:name_list.sort()  对元素按照ASCII码进行排序
        python3 里面不能同时sort int 和 str类型
    反转顺序:name_list.reverse()  对列表中的元素进行反转操作
    切片:name_list[0:3]  切取索引值从0-2的值(切片顾头不顾尾)
    扩展:name_list.extend(name_list2) 在一个列表后面追加另一个列表的元素,或者追加一个变量中的单个字符
5.元组
    >>> namelist = ("swht","test")
    >>> type(namelist)
        <class 'tuple'>
    索引:>>> namelist.index('swht') #查找某个字符串的索引值
             0
    统计:>>> namelist.count('swht') #统计某个字符串出现的次数
             1
6.字典(无序)
    参考:http://www.jb51.net/article/47990.htm

    不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住
    键必须不可变,所以可以用数,字符串或元组充当,所以用列表就不行

    dict = {"swht":"test123","shen":"test124","test":"test125"}
    访问字典里的值:
        >>> dict["swht"]
            'test123'
    增加字典里的值:
        >>> dict["alex"] = "test126"
        >>> dict
        {'test': 'test125', 'shen': 'test124', 'swht': 'test123', 'alex': 'test126'}

    删除字典当中的元素:
        >>> del dict["test"]
        >>> dict
        {'shen': 'test124', 'swht': 'test123', 'alex': 'test126'}
        >>>                
    清空字典里的所有条目:
        >>> dict.clear()
        >>> dict
        {}
    删除字典:del dict

九、文件操作

简单操作:
    filename = open("文件路径","模式")    #打开文件
    filename.write('内容')    #往文件中写入内容
    filename.read()        #一次性加载文件中的内容到内存
    filename.readlines()    #一次性加载所有的内容到内存,并根据行分割成字符串
    filename.close()    #关闭文件句柄

十、作业

作业一:编写登录接口

作业二:多级菜单