【python自动化第三篇:python入门进阶】

鸡汤:

  多学习,多看书。

  推荐书籍:《追风筝的人》,《林达看美国》,《白鹿原》

本节知识点

  1. 集合及其操作
  2. 文件操作
  3. 函数与函数式编程
  4. 递归

一.集合及其操作

   集合(set):把不同的元素组成一起形成集合,是python基本的数据类型。下面是set的基本操作:

   关系测试:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:wanghui
#set_1 = set([123,345,678])               #创建set
l1 = [11,22,33,44,55]
l2 = [33,44,55,66]
l1_s = set(l1)                            #将列表转换成set
l2_s = set(l2)
#####关系测试
#交集:取出两者相同的部分
print(l1_s.intersection(l2_s))
print(l1_s & l2_s)
#并集:两者合并起来去重
print(l1_s.union(l2_s))
print(l1_s | l2_s)
#差集:两者之间一方有而另一方没有的
print(l1_s.difference(l2_s))
print(l1_s - l2_s)
#子集 or 父集:两者有相互包含的关系,如果我中有你也就是说你是我的子集,返回True,反之为false
print(l1_s.issubset(l2_s))                #子集判断
print(l1_s.issuperset(l2_s))              #父集判断
#对称差集:去除交集之后剩下的集合元素
print(l1_s.symmetric_difference(l2_s))
print(l1_s ^ l2_s)
#二者是否有交集
print(l1_s.isdisjoint(l2_s))              #返回True表示二者无交集,False表示有交集

  基本操作:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:wanghui
l1_s = set([123,456,891,22,33])
#add操作:单独添加一个集合元素的操作(集合也是无序的)
l1_s.add(888)
print(l1_s)
#update操作:添加多个集合元素
l1_s.update([333,1243,45,2332])
print(l1_s)
#remove()操作:删除其中的一项
l1_s.remove(45)
print(l1_s)
#len操作:确定元素个数
print(len(l1_s))
#in操作:成员判断操作
"x" in l1_s
"x" not in l1_s
#pop操作:删除任意的一个,并返回删除的元素
print(l1_s.pop())
#discard操作:和remove不同的一点在于:discard在指定删除不存在的元素时不会报错(返回None),然而remove会报错
print(l1_s.discard("sdadasd"))

二.文件操作

  文件的操作过程要注意到:文件的代开,文件的读取,文件的写入和创建以及到最后的追加和关闭操作

  文件实例

Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
就如舌尖上的雨露
I teased at life as if it were a foolish game
我戏弄生命 视其为愚蠢的游戏
The way the evening breeze
就如夜晚的微风
May tease the candle flame
逗弄蜡烛的火苗
The thousand dreams I dreamed
我曾千万次梦见
The splendid things I planned
那些我计划的绚丽蓝图
I always built to last on weak and shifting sand
但我总是将之建筑在易逝的流沙上
I lived by night and shunned the naked light of day
我夜夜笙歌 逃避白昼赤裸的阳光
And only now I see how the time ran away
事到如今我才看清岁月是如何匆匆流逝
Yesterday when I was young
昨日当我年少轻狂
So many lovely songs were waiting to be sung
有那么多甜美的曲儿等我歌唱
So many wild pleasures lay in store for me
有那么多肆意的快乐等我享受
And so much pain my eyes refused to see
还有那么多痛苦 我的双眼却视而不见
I ran so fast that time and youth at last ran out
我飞快地奔走 最终时光与青春消逝殆尽
I never stopped to think what life was all about
我从未停下脚步去思考生命的意义
And every conversation that I can now recall
如今回想起的所有对话
Concerned itself with me and nothing else at all
除了和我相关的 什么都记不得了
The game of love I played with arrogance and pride
我用自负和傲慢玩着爱情的游戏
And every flame I lit too quickly, quickly died
所有我点燃的火焰都熄灭得太快
The friends I made all somehow seemed to slip away
所有我交的朋友似乎都不知不觉地离开了
And only now I'm left alone to end the play, yeah
只剩我一个人在台上来结束这场闹剧
Oh, yesterday when I was young
噢 昨日当我年少轻狂
So many, many songs were waiting to be sung
有那么那么多甜美的曲儿等我歌唱
So many wild pleasures lay in store for me
有那么多肆意的快乐等我享受
And so much pain my eyes refused to see
还有那么多痛苦 我的双眼却视而不见
There are so many songs in me that won't be sung
我有太多歌曲永远不会被唱起
I feel the bitter taste of tears upon my tongue
我尝到了舌尖泪水的苦涩滋味
The time has come for me to pay for yesterday
终于到了付出代价的时间 为了昨日
When I was young
当我年少轻狂
As rain upon my tongue
就如舌尖上的雨露
I teased at life as if it were a foolish game
我戏弄生命 视其为愚蠢的游戏
The way the evening breeze
就如夜晚的微风
May tease the candle flame
逗弄蜡烛的火苗
The thousand dreams I dreamed
我曾千万次梦见
The splendid things I planned
那些我计划的绚丽蓝图
I always built to last on weak and shifting sand
但我总是将之建筑在易逝的流沙上
I lived by night and shunned the naked light of day
我夜夜笙歌 逃避白昼赤裸的阳光
And only now I see how the time ran away
事到如今我才看清岁月是如何匆匆流逝
Yesterday when I was young
昨日当我年少轻狂
So many lovely songs were waiting to be sung
有那么多甜美的曲儿等我歌唱
So many wild pleasures lay in store for me
有那么多肆意的快乐等我享受
And so much pain my eyes refused to see
还有那么多痛苦 我的双眼却视而不见
I ran so fast that time and youth at last ran out
我飞快地奔走 最终时光与青春消逝殆尽
I never stopped to think what life was all about
我从未停下脚步去思考生命的意义
And every conversation that I can now recall
如今回想起的所有对话
Concerned itself with me and nothing else at all
除了和我相关的 什么都记不得了
The game of love I played with arrogance and pride
我用自负和傲慢玩着爱情的游戏
And every flame I lit too quickly, quickly died
所有我点燃的火焰都熄灭得太快
The friends I made all somehow seemed to slip away
所有我交的朋友似乎都不知不觉地离开了
And only now I'm left alone to end the play, yeah
只剩我一个人在台上来结束这场闹剧
Oh, yesterday when I was young
噢 昨日当我年少轻狂
So many, many songs were waiting to be sung
有那么那么多甜美的曲儿等我歌唱
So many wild pleasures lay in store for me
有那么多肆意的快乐等我享受
And so much pain my eyes refused to see
还有那么多痛苦 我的双眼却视而不见
There are so many songs in me that won't be sung
我有太多歌曲永远不会被唱起
I feel the bitter taste of tears upon my tongue
我尝到了舌尖泪水的苦涩滋味
The time has come for me to pay for yesterday
终于到了付出代价的时间 为了昨日
When I was young
当我年少轻狂呵呵呵呵呵呵呵呵呵!!!!
View Code

      基本操作:

###文件读取操作
#data = open("yesterday",encoding="utf-8").read()    #读取所有的内容
# f = open("yesterday",encoding='utf-8')
# data = f.read()
# data2 = f.read()
# print(data)
# print("-----》》》",data2)


###文件写入操作
# f =open("yesterday","w",encoding='utf-8')           #写入操作:如果文件不存在则会创建新文件,否则会覆盖原来的文件
# f.write("我勒个去!!!")
# f.close()


###文件追加操作
f = open("yesterday","a",encoding='utf-8')            #追加操作:不能执行读操作
f.write("呵呵呵呵呵\n呵呵呵呵!!!!")
f.close()

  读取操作:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

f = open("yesterday","r",encoding='utf-8')
for i in range(5):
     print(f.readline())        #读取前5行


for line in f.readlines():     #readlines()将文件按照列表读取
    print(line.strip())         #去掉空格和换行

  比较高效的读取方式:

count = 0
for line in f:
    if count == 9:                                             #读取到第九行,并打印
        print("------分割线---------")
        count += 1
        continue
    print(line.strip())
    count += 1

   其他方法:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
f = open("yesterday","r",encoding='utf-8')
print(f.tell())             #读取文件行位置(按字符个数计数的)
#print(f.readline())        #按行读取
print(f.read(5))            #读取前5个字符
print(f.tell())
f.seek(0)                    #seek只能够按照字符所在位置返回,不能够按行返回
print(f.encoding)           #打印文件编码
print(f.fileno())           #返回文件在内存中的编号
print(f.name)               #打印文件名称
#f.seekable()                #用于终端设备文件读取的移回
print(f.readable())          #判断文件是否可读
print(f.writable())          #判断文件是否可写
print(f.flush())             #将内容从内存刷到硬盘
f.truncate(10) #截断

  文件读写进阶:

   打印进度条程序:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:wanghui
import sys,time
for i in range(50):
    sys.stdout.write("#")
    sys.stdout.flush()
    time.sleep(0.1)

  读写进阶:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:wanghui
#f = open('yesterday','r+',encoding='utf-8')              #读写
#f = open("yesterday",'w+',encoding='utf-8')                 #写读模式
#f = open("yesterday",'a+',encoding='utf-8')               #追加读
f = open('yesterday','rb')             #二进制格式去读,不能传入encoding(网络传输,)
f = open("yesterday",'wb')             #二进制格式去写
f.write('helloworld'.encode())
# print(f.readline())
# print(f.readline())
# print(f.readline())
# f.write("----哈哈哈哈哈111----\n")
# f.write("----哈哈哈哈哈2222----\n")
# f.write("----哈哈哈哈哈3333----\n")
# f.write("----哈哈哈哈哈4444----\n")
# f.write("----哈哈哈哈哈5555----\n")
# print(f.tell())
# f.seek(10)
# print(f.readline())

  文件修改(需要读取和修改文件两步操作)

#!/usr/bin/env python
# -*- coding:utf-8 -*-
f = open("yesterday",'r',encoding='utf-8')
f_new = open("yesterday2.bak",'w',encoding='utf-8')

for line in f:                                                               #遍历旧文件
    if "肆意的快乐" in line:                                                  #如果肆意的快乐在读取到的行中
        line = line.replace("肆意的快乐","肆意的快乐等我去享受!")               #替换操作
    f_new = f_new.write(line)                                               #写入操作
f.close()                                                                   #文件关闭
f_new.close()

  with操作:

with open("yesterday",'r',encoding='utf-8') as f\
        ,open("yesterday2",'w',encoding='utf-8') as f_new:

编码问题:

 

python 2.7的编码问题

#!/usr/bin/env python
#-*-coding:utf-8 -*-
import sys
print(sys.getdefaultencoding())
s="哈喽啊!!"
s_to_gbk = s.decode('utf-8').encode('gbk')
print(s_to_gbk)
print(type(s))

  

python3的写法:
#!/usr/bin/env python
# -*- coding:gbk -*-
import sys
print(sys.getdefaultencoding())
s = "哈哈哈,好屌啊!!"
s_to_gbk = s.encode('gbk')
print(s_to_gbk)

三、函数式编程

函数的定义:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
def test(x):
    "the function of description!"
    x+=1
    return x
#def:定义函数的关键字
#test:函数名
#(x):x为形式参数
#"":定义函数的描述
#x+=1:泛指代码中的处理逻辑
#return:定义返回值

函数和过程:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

#函数
def fun1():
    '''testing'''
    print("in the func1")
    return 0


#过程:没有return这个的函数
def func2():
    '''testing2'''
    print("in the funct2!")

x=fun1()
y=func2()

函数的优点:实现代码的拓展性;简化代码;保持数据的一致性; 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:wanghui
import time                                           #导入时间模块

def logger():
    time_format = '%Y-%M-%d %X'         #时间格式定义
    time_current = time.strftime(time_format)    #当前时间的定义
    with open('a.txt','a') as f:                               #文件追加
        f.write('%s wndaction\n'%time_current)
#测试函数,
def test1():                                            
    print('test1 starting action')
    logger()


def test2():
    print('test2 starting action')
    logger()

def test3():
    print('test3 starting action')
    logger()
#执行顺序
test1()
test2()
test2()

函数的返回值(return):代码执行结果的返回值可以通过返回值体现出代码执行的状态结果是什么样的

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:wanghui
def test1():
    print("in the test1")
    return 0       #结束程序,并返回值,不再执行此函数体内的下面部分代码
    print('test end')
def test2():
    print("in trh test2")
    
def test3():
    print("in trh test3")
    return 1,'hello',['wanghui','hehehe'],{'name':'wanghui'}   #返回值的类型比较多,最终将返回到一个元组中

x = test1()
y = test2()
z = test3()
print(x)

 位置参数和关键字调用的使用:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:wanghui
def test(x,y):
    print(x)
    print(y)
test(1,2)          #这里的1,2是x,y的位置参数,也叫作实参是内存中实际存在的值,而x,y为形参,不会占内存空间
##所有的形参和实参是一一对应的不能多也不能少
test(x=3,y=4)      #这是关键字调用的表示方法,要记住关键字调用和位置参数的位置:位置参数要位于关键字调用之前

 默认参数的使用

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:wanghui
def test(x,y=2):
    print(x)
    print(y)

test(1,3)   #调用函数的时候,默认参数是非必传参数,用于默认安装路径等,然后之后的传递相当于是修改默认参数
#默认安装值,以及连接数据库的端口号

  参数组的应用 :

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:wanghui】
#第一种参数组:接受N个位置参数转换成元组的方式
def test(*args):
   print(args)

test(2,3,45)        #解决实参不固定的情况下就需要使用参数组来解决这个问题(*args),输出为元组
test(*[1,2,34,5,6,432,23])    #结合列表


#第二种参数组
def test1(x,*args):
    print(x)
    print(args)

test(1,2,3,4,56,8,79,0)      #可以传递任意的参数值,传多少都可以

#第三种参数组:前俩中都是能转成不同形式(半元组和全元组形式),将N个关键字参数转换成键值对形式存放
#可以接受字典的参数组
def test2(**kwargs):
    print(kwargs)
#test2(name="alex",age=8,sex="male")     #将N个关键字参数转换成键值对形式存放
test2(**{'name':'wanghui','age':22})
#test2(1,2,3,4,5,6)                         #不能转成字典形式


#结合位置参数使用
def test3(name,age=23,**kwargs):                    #默认参数要放到参数组之前,否则会报错
    print(name)
    print(kwargs)
#test3('wanghui','cdfv','ewwqd')             #这样错误
test3('wanghui',gender="male")

#结合第一种参数组实验
def test4(name,age=22,*args,**kwargs):
    print(name)
    print(args)
    print(kwargs)
test4('wanghui',age=25,hobby='IT',birthday=1991)  #结果会返回一个空的元组,因为后面的关键字参数被转成了字典,由于不存在位置参数,所以元组为空

  局部变量和全局变量:

##局部变量:在子程序中局部变量器作用

# def change_name(name):
#     print("\033[31mbefore change :\033[0m",name)
#     name = "WANGHUI"
#     print("\033[41mafter chang:\033[0m",name)
#
# name ='wanghui'
# change_name(name)
# print(name)


##全局变量
school = "oldboy edu"

def change_name(name):
    school ="mage edu"
    print("before change",name,school)
    name = 'WANGHUI'
    age =24
    print("after change",name)

name = "wanghui"
change_name(name)
print(name)
print(school)      #保持输出oldboy edu 而mage edu指示函数体内的局部变量,不能被全局变量调用

##局部变量上位
school = "oldboy edu"

def change_name(name):
    global school
    school ="mage edu"
    print("before change",name,school)
    name = 'WANGHUI'
    age =24
    print("after change",name)

name = "wanghui"
change_name(name)
print(name)
print(school)                #强制改变全局变量,所以mage edu上位成功

  特别注意:

#局部变量里面对于字符串和数字的修改不影响全局变量,然而要是序列类型的话,只要徐改了局部变量里对应的元素则就影响了全局变量
#原因在于:只要能改就行,哈哈哈哈!!
names=['wanghui','chenyibo','liming'] def test(): names[0] = "王辉" print(names) test() print(names)

  递归:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:wanghui
#递归:要有明确的结束条件;深入递归一次 问题规模要比前一次减少;递归效率不高会导致栈溢出
# def calc(n):
#     print(n)
#     return calc(n+1)   #会打印999次,然后就报错了
# calc(1)

def calc(n):
    print(n)
    if int(n/2) > 0:
        return calc(int(n/2))
    print(("--->\n",n))     #这里输出1,原因是最后结果除下来为0,所以打印0对应的结果1

calc(10)

  函数式编程:是一种编程范式。它的特点就是允许函数本身作为参数传入另一个函数,还允许返回一个函数。python针对函数式编程不是太全面。学习函数式变成比较好的编程语言有lisp,hashshell,erlang等。

  高阶函数:

    变量可以指向函数,函数的参数能够接收变量,name一个函数就可以接受另一个函数作为参数

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:wanghui
def add(a,b,f):
    return f(a)+f(b)
res = add(3,-6,abs)                        
print(res)

 今天作业:

程序1: 实现简单的shell sed替换功能

  程序解析:

 

程序2:修改haproxy配置文件 

 

 

posted @ 2016-08-10 03:38  valiente  阅读(3072)  评论(0编辑  收藏  举报