首页 > 技术文章 > Python学习之路第三周汇总

source12 2018-09-20 21:11 原文

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:Source
#列表转集合,集合作用与特点:去重复、无序的
list=['pengfeiji','dabaojian','wushuishui',1,2,2,1,3,4,5,6]
review_gather=set([2,4,6,'pengfeiji',7,8,10,15])
list_to_gather=set(list)
print(list,list_to_gather)
#求交集
print(list_to_gather.intersection(review_gather))
print(list_to_gather & review_gather)
#求并集
print(list_to_gather.union(review_gather))
print(list_to_gather | review_gather)
#求差集
print(list_to_gather.difference(review_gather))#list_to_gather有而review_gather没有
print(review_gather.difference(list_to_gather))#类似上述
print(list_to_gather - review_gather)
#对称差集,去除公共部分
print(list_to_gather.symmetric_difference(review_gather))
print(review_gather.symmetric_difference(list_to_gather))
print(list_to_gather ^ review_gather)
#更新
list_to_gather.difference_update(review_gather)#从list_to_gather中删除review_gather中有的元素
print(list_to_gather)
#子集
print(review_gather)
list_standby_gather=set([4,2,])
print(list_standby_gather.issubset(review_gather))
#父集
print(review_gather.issuperset(list_standby_gather))
#基本操作
copy_gather=review_gather.copy()
print(copy_gather)
copy_gather.discard(4)#删除指令,不存在不会报错
copy_gather.pop()#删除指令,随机删除一项
print(copy_gather)
import copy
deepcopy_gather=copy.deepcopy(review_gather)
deepcopy_gather.remove(10)#,删除指令不存在会报错
print(deepcopy_gather)
print(review_gather)
review_gather.add(1)#添加指令,添加一项。
review_gather.update([18,19,20])#添加指令添加多项,记得用”[]“阔起来
print(review_gather)
#测试长度
print(len(review_gather))
#测试x是否在s里面
print(2 in review_gather)
#文件操作
#读文件,文件句柄f=文件内存对象,’\‘是转义符
date = open('shell_sed_replace',encoding='utf-8',).read()
print(date)
f = open('shell_sed_replace','r')
print(f.readline())#读一行
print(f.readline())#每次光标指向末尾
print(f.readlines())#适合小文件,与read()类似,不过是将每一行存为列表中的一个元素
#打印句柄
print(f.tell())#tell() 方法返回文件的当前位置,即文件指针当前位置。
f.seek(35)#改变指针位置
print(f.readline())

#写文件,文件的正确打开姿势,写完后要关闭。
f1 = open('shell_sed_replace2','w+',encoding='utf-8',)
f1.write('我喜欢你')
#文件模式
f2 = open('shell_sed_replace2','r')#读文件
#变成迭代器, 迭代器是访问集合元素的一种方式。迭代器对象从集合的第一个元素开始访问,
# 直到所有的元素被访问完结束。迭代器只能往前不会后退。
#for line in f2:
#    print(line.strip())
f3 = open('shell_sed_replace2','w')#写文件,会将里面原有的内容清空
f3.write('微笑很久\n静静感受这份爱\n怕你会把我宠坏\n你的温柔像\n还有没有人会知道\n多想藏着你的好')
f4= open('shell_sed_replace2',mode='a',encoding='utf-8')#追加
f4.write('\n我舍不得离开')
#语法
f4.detach()#编程过程可以改变语法
#print(f4.encoding)#打印编码方式
#print(f4.fileno())#返回文件在内存中的编号,提示错误underlying buffer has been detached
#print(f4.seekable())#判断是否可以设置指针
#print(f4.readable())#判断文件是否可读
#print(f4.name)#打印文件名字
#print(f4.isatty)#判断是否是一个终端,比如和打印机交互
#print(f4.closed)#判断文件是否关闭
#print(f4.flush())#强制将内存的东西刷到硬盘中去。
#f4.truncate(10)#截取文件一部分,只能从头开始截,不填会清空
#进度条
import sys,time
for i in range(20):
    sys.stdout.write('*')
    sys.stdout.flush()
    time.sleep(0.1)
#sys模块,stdout标准输出,stdin标准输入。
#time模块,sleep。
#读写操作
'''f5 = open('文件名','r+',encoding='utf-8')
f5.read()
f5.write()#写均只能从末尾开始写'''
#二进制读
f6 = open('attempt','rb')
print(f6.read().decode())#译码之后就可以正常显示了
#二进制写
f7 = open('attempt','wb')
write_f7=f7.write('attempt'.encode('utf-8'))#编码后可以写入
f7.close()#不关闭的话依旧会将“attempt”写入文件
#写读操作,会创建一个新文件再写
f8 = open('attempt','w+')
f8.write('i love you'.center(50,'*').title())
print(f8.read())
#“U”表示在读取时,可以将\r \n \r\n自动转换成\n(与r和r+模式一起使用)rU,r+U
#自动关闭文件
'''with open('文件名','文件模式')as f,open('文件名2','文件模式')as f2:
    pass'''
#修改文件内容
with open('old_file','r')as file1,open('new_file','w')as file2:
    for line in file1:
        if '一个人的夜' in line:
            line=line.replace('一个人的夜','两个人的夜')
        file2.write(line)
#python代码规范:一行不超过80个字符
#字符编码和转码,若str对象调用encode会默认先按系统默认编码方式decode成unicode对象再encode,
# 忽视了中间默认的decode往往导致报错。
import sys
contend='大鸟同学'
print(contend.encode('utf-8'))#encode后加上编码后的对象,decode后加上译码前的对象
print(contend.encode('utf-8').decode('utf-8').encode('GBK'))#utf-8转gbk
#文件头的作用是,文件编码是什么,就声明什么。
print(sys.getdefaultencoding())#查询系统的默认编码
print(contend.encode('GBK'))
#函数
#面向对象-类-class
#面向过程-过程-def
#函数式编程-函数-def,与面向过程的一个区别是:面向函数有返回值。
#编程中函数的定义:函数是逻辑结构化、过程化的一个方法。
#函数返回值(return):返回值=0,返回0;返回值=1,返回object;返回值>1,返回tuple
#函数调用:形参、实参
def test(x,y):#其中x、y就是形参
    print(x)
    print(y)
    return 'OK'
test(1,2)#位置调用,其中1,2是实参
test(x=1,y=2)#关键字调用。注意关键子参数不能写在位置参数前面。
test(1,y=2)
def test2(a=2,b=3):#设置默认参数两个都要设置,特点:非必需,可有可无。用途:默认安装。
    print(a)
    print(b)
    return 'No'
def test3(*args):#参数组,标准的是*args,可以输入多个实参
    print('is very good.'.title())
    return 12,'as',['sa','sadf'],{'sa':['12','sadf']}#可以返回数字、字母列表、字典
test2()
casual=test3(3000)
casual2=test3(*[1,2,3,4,5,6])#参数组写法
print(casual)
def test4(**kwargs):#字典方式,标准的是**kwargs
    print(kwargs)
    return "字典方式圆满完成"
#实参写法,两种
test4(behaviour='good')#**kwargs在使用实参时不能有位置参数。
test4(**{'hello':23,'weather':'fine'})
#写一个记录事件执行时间的函数
def time_record(*args):
    time_format='%Y-%m-%d %X'
    time_current=time.strftime(time_format)
    with open('time_succeed','r+')as action:
        action.write('%s ction is very succeed.'%(time_current))
#函数式编程的好处:1、代码的重复利用 2、保持一致性 3、可扩展性
def topo(*args):
    a=10
    print('number:',a)
topo()
#print(a)#局部变量,在子程序中定义的变量,作用域在定义该变量的子程序。如果要使局部变量在全局有效。则添加一个global在参数前面。但是最好不要使用!
b=4
def topo2(*args):
    global b#整形、字符串改不了。
    b=2
    print('number:',b)
topo2()
print(b)
list_change=['can change','are you sure']
def topo3(*args):
    list_change[1]='还真的可以'#列表、字典、集合、类可以改。
    print(list_change)
topo3()
print(list_change)
#全局变量。程序一开始定义的变量。作用域在整个程序。当全局变量和局部变量名字一样的时候。定义局部变量的子程序内,局部变量起作用,
#其它的全局变量起作用
#递归。定义:在函数内部,可以调用其它函数,如果一个函数在内部调用自身本身,则这个函数就是递归函数。
#递归的上限是999左右。
#递归的特性:1、必须有一个明确的结束条件。2、每次进入更深一层递归时,问题规模相比上次递归都应有所减少。
#3、递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈
# 就会增加一层栈帧,每当函数返回,栈就会减少一层,由于栈的大小不是无限的。所以,递归调用的次数过多,会导致栈溢出。)
def recurrence(number):
    print(number)
    if number>0:
        return recurrence(number-1)
recurrence(10)
#高阶函数
def high_order_function(a,b,f):
    print('现在将进行绝对值运算。')
    return f(a)+f(b)
a=high_order_function(5,-5,abs)
print(a)
#修改haproxy配置文件
def cycle(enter,finish,handle):
    for line in handle:
        if enter in line:
            for line in handle:
                print(line)
                if finish in line:
                    break
def Dynamic(old,new,handle,handle2):
    for line in handle:
        if old in line:
            line=line.replace(old,new)
        handle2.write(line)
def addition(add,add_content,handle,handle2):
    for line in handle:
        handle2.write(line)
        if add in line:
            handle2.write('        ')
            handle2.write(add_content)
            handle2.write('\n')
        elif add=='q':
            break
        else:
            pass
def remove(delete_content,handle,handle2):
    for line in handle:
        if delete_content in line:
            continue
        elif delete_content == 'q':
            break
        else:
            pass
        handle2.write(line)
with open('haproxy_configuration','r+')as f,open('new_haproxy','w+')as f2:
    query=input('Please enter query data:')
    if query =='global':
        for line in f:
            print(line)
            if 'defaults'in line:
                break
    elif query == 'defaults':
        cycle('defaults','listen',f)
    elif query == 'listen':
        cycle('listen','frontend',f)
    elif query == 'frontend' :
        cycle('frontend','backend',f)
    elif query == 'backend':
        for line in f:
            if query in line:
                f.readline()
                for line in f:
                    print(line)
    elif query == 'modification':
        for line in f:
            print(line)
        while True:
            modification=input('What would you like to change:')
            modification_new=input('What do you want to replace:')
            if modification_new=='q' or modification=='q':
                break
            f.seek(0)
            Dynamic(modification,modification_new,f,f2)
            '''for line in f:
                if modification in line:
                    line=line.replace(modification,modification_new)
                f2.write(line)'''
    elif query == 'add':
        for line in f:
            print(line)
        f.seek(0)
        add = input('Please enter you want to add location.')
        add_content=input('Please enter you want to add content.')
        addition(add,add_content,f,f2)
    elif query == 'del':
        for line in f:
            print(line)
        f.seek(0)
        delete_content = input('Please enter you want to delete content.')
        remove(delete_content,f,f2)
    else:
        print("\033[31;1mPlease enter accurate data.\033[0m")

  

推荐阅读