python的学习第三天
第三天带来的是集合和文件的操作以及函数
集合
集合:set 是一个无序的元素集合,支持并、交、差及对称差等数学运算, 但由于 set 不记录元素位置,因此不支持索引、分片等类序列的操作。
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = "tao" list1 = [1,2,3,4,5,4,7,2] list1 = set(list1) #把列表换成集合 print(list1,type(list1)) #{1, 2, 3, 4, 5, 7} <class 'set'> 转换后就没有重复的了,类型也变成了set 集合类型 list2 = set([1,3,5,7,9,8,0]) #直接声明一个集合 print(list1,list2) #{1, 2, 3, 4, 5, 7} {0, 1, 3, 5, 7, 8, 9} print(list1.intersection(list2)) #交集 #{1, 3, 5, 7} print(list1.union(list2)) #{0, 1, 2, 3, 4, 5, 7, 8, 9} #并集 print(list1.difference(list2)) #{2, 4} 差集 list1里面有的list2中没有的 print(list2.difference(list1)) #{0, 8, 9} list2中有而list1中没有的差集 print(list1.issubset(list2)) #判断list1是不是list2的子集 print(list2.issubset(list1)) #判断list2是不是list1的子集 print(list1.issuperset(list2))#判断list1是不是list2的父集 print(list1.symmetric_difference(list2)) #把两个列表共同的去掉,把不用的组合起来的集合 list3=set([8,9]) print(list1,list3) #{0, 2, 4, 8, 9} #{1, 2, 3, 4, 5, 7} {8, 9} print(list1.isdisjoint(list3)) #True 判断是否有交集,没有就正确 ###用符号来表示 print(list1 & list2) #交集表示方法 print(list1 | list2) #并集表示方法 print(list1 - list2) #在list1中不在list2中 print(list1 ^ list2) #对称差集 ### print(list3) #{8, 9} list3.add(11) #添加 print(list3) #{8, 9, 11} list3.update([22,33,44]) #添加多个元素 print(list3) #{33, 8, 9, 11, 44, 22} list3.remove(44) #删除一个,集合没有重复的,删除没有的会报错 print(list3) list3.pop() #任意删除一个 list1.discard(88) #删除,没有的会返回none 这是和pop的区别
文件的操作
对文件的操作流程:打开文件得到文件句柄并赋值给一个变量,通过对这个句柄(就是文件的属性)进行操作,最后记得close关闭这个文件,(不关闭会占系统资源)
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = "tao" f1 = open('aa.txt',encoding='utf-8').read() #直接读这个文件,一下就读完了 f0 = open('aa.txt',encoding='utf-8') #这是一个文件句柄,记录的是文件的各种属性 print(f1) # 唐·李白 # # 日照香炉生紫烟,遥看瀑布挂前川。 # 飞流直下三千尺,疑是银河落九天。 # hello python >>文本的内容 f3 = open ('aa.txt','w',encoding='utf-8') #w是写入的意思。 f3.write('偶像李白') #这样发现aa.txt里面的内容全部被清空,就剩下新写如的了。 f3.close()# 关闭文件 f4 = open('aa.txt','a',encoding='utf-8') #append 追加,在最后加入 f4.write('\n 啊 七夕,你比巴西少以西') # 偶像李白 # 啊 七夕,你比巴西少以西 #可以看到追加到后面了 ######要是用以上的r w a 三种情况的时候,读就值能读,不能写,会报错,要是写就能写不能读,追加就能追加不能读####
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建;存在则删除内容;】
- a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+,可读写文件。【可读;可写;可追加】
- w+,写读
- a+,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
- rb 只读模式
- wb 写模式
- ab 追加模式
用到的文件内容:
aa.txt
唐·李白
日照香炉生紫烟,遥看瀑布挂前川。
飞流直下三千尺,疑是银河落九天。
hello python >>文本的内容
aaa.txt
It's been a long day without you my friend 没有老友你的陪伴 日子真是漫长 And I'll tell you all about it when I see you again 与你重逢之时 我会敞开心扉倾诉所有 We've come a long way from where we began 回头凝望 我们携手走过漫长的旅程 Oh I'll tell you all about it when I see you again 与你重逢之时 我会敞开心扉倾诉所有 When I see you again 与你重逢之时 Damn who knew all the planes we flew 谁会了解我们经历过怎样的旅程 Good things we've been through 谁会了解我们见证过怎样的美好 That I'll be standing right here 这便是我在你眼前出现的原因 Talking to you about another path 与你聊聊另一种选择的可能 I know we loved to hit the road and laugh 我懂我们都偏爱速度与激情 But something told me that it wouldn't last 但有个声音告诉我这美好并不会永恒 Had to switch up look at things 我们得变更视野 different see the bigger picture 转向更为辽阔的天地 Those were the days hard work forever pays 有付出的日子终有收获的时节 Now I see you in a better place 此刻 我看到你走进更加美好的未来 Now I see you in a better place 此刻 我看到你走进更加美好的未来 How could we not talk about family 当家人已是我们唯一的牵绊 when family's all that we got? 我们怎么能忘却最可贵的真情 Everything I went through 无论历经怎样的艰难坎坷 you were standing there by my side 总有你相伴陪我度过 And now you gonna be with me for the last ride 最后一段征程 我更需要你的相伴 It's been a long day without you my friend 没有老友你的陪伴 日子真是漫长 And I'll tell you all about it when I see you again 与你重逢之时 我会敞开心扉倾诉所有 We've come a long way from where we began 回头凝望 我们携手走过漫长的旅程 Oh I'll tell you all about it when I see you again 与你重逢之时 我会敞开心扉倾诉所有 When I see you again 与你重逢之时 First you both go out your way 一开始你们总是追随你们心中的步伐 And the vibe is feeling strong and what's 热忱累积 信念不变
练习:
1 读一个文件的全部
f1 = open('aa.txt','r',encoding='utf-8') # print(f1.readline()) #读取一行 for line in f1.readlines(): print(line.strip()) #打印,strip去掉空格和\n换行 # 唐·李白 # # 日照香炉生紫烟,遥看瀑布挂前川。 # 飞流直下三千尺,疑是银河落九天。 # hello python >>文本的内容
2 读取一个文件的全部,遇到第四行就打印其他的
for index,line2 in enumerate(f1.readlines()): if index == 4 : print('我是第四行') print(line2.strip()) 唐·李白 # 日照香炉生紫烟,遥看瀑布挂前川。 # 飞流直下三千尺,疑是银河落九天。 # 我是第四行 # hello # python >> 文本的内容
3 比较高效率的读文件,上面的readlines适合读小文件,几个G的文件需要用for
count = 0 for line in f1: if count == 4: print('我是第四行哦!!!') print(line) count +=1 ##变成了迭代器,比上面的效率高,不是全部读到内存,而是一行读完就不要以前的了一行处理一行和awk一样 # 唐·李白 # # # # 日照香炉生紫烟,遥看瀑布挂前川。 # # 飞流直下三千尺,疑是银河落九天。 # # 我是第四行哦!!! # hello python >>文本的内容
4 光标的位置tell
f1 = open('aa.txt','r',encoding='utf-8') print(f1.tell()) #tell光标的位置 print(f1.read(17)) print(f1.tell()) #读17的时候光标的位置 # 0 # 唐·李白 # # 日照香炉生紫烟,遥看瀑 # 48
5 返回光标到指定位置 seek
f1 = open('aa.txt','r',encoding='utf-8') print(f1.readline()) print(f1.readline()) print(f1.readline()) print(f1.tell()) #第三行读完后这时的光标位置 f1.seek(0) #反会到0 print(f1.readline()) #这时就读到第一行了 # 唐·李白 # # # # 日照香炉生紫烟,遥看瀑布挂前川。 # # 65 # 唐·李白
6 打印进度条小技巧
print(f1.encoding) #编码 print(f1.fileno()) #内存的编号 f1.flush() #更新到硬盘 ########################### for i in range(80): sys.stdout.write("#") sys.stdout.flush() time.sleep(0.1) #打印进度条 #####
#要先引入下面的模块
import sys
import time

7 写一个sed一样的替换小程序:
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = "tao" import sys f = open('aaa.txt','r',encoding='utf-8') f_new = open("aaa_new.txt",'w',encoding='utf-8') find_str = input('请输入要替换的内容:') replace_str = input('请输入要替换后的内容:') for line in f: if find_str in line: line = line.replace(find_str,replace_str) f_new.write(line) f.close() f_new.close()

8 为了避免打开文件后忘记关闭,可以通过管理上下文,即:
with open('文件','r+') as f:
f.write()
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
with open('文件1') as f1, open('文件2') as f2:
代码
如果想清晰的打开可以
with open('文件1') as f1,\
open('文件2') as f2:
代码
字符编码与转码
详细文章:http://www.cnblogs.com/luotianshuai/articles/5735051.html
utf-8到GBK还是gbk到utf-8都是经过了decode换成了Unicode后再经过encode转换成相应的编码


在python3中unicode是默认,他们3个相应的转码如下:
#!/usr/bin/env python # -*- coding:utf-8 -*- 这里只是文件编码,而pytho3还是默认uncode __author__ = "tao" import sys print(sys.getdefaultencoding()) str1 = "我爱python" str1_to_unicode = str1.encode('utf-8') print(str1_to_unicode) #显示的是utf-8的编码格式 str1_to_gbk = str1.encode('utf-8').decode('utf-8').encode('gbk') #显示的是gbk的编码格式 print(str1_to_gbk) #python2默认是gbk
函数和函数式编程
函数可以让代码重复利用,让逻辑清晰,程序容易扩展, 关键字def:
1. 一个小程序,给日志记录加上时间:
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = "tao" import time def logger_test(): time_format='%Y-%m-%d %X' time_current=time.strftime(time_format) with open('aaa.txt','a+') as f: f.write('time %s end action'%time_current) f.write('\n') def test1(): print('test1:') logger_test() def test2(): print('test2:') logger_test() def test3(): print('test3:') logger_test() test1() test2() test3()
2. 函数可以返回任意值,没有返回none
def test01(): print('test01') def test02(): return 0 def test03(): return 0, 'hello', ['aa', 'cc'], {'wahaha': '123'} t1 = test01() t2 = test02() t3 = test03() print(t1) print(t2) print(t3) test01 None 0 (0, 'hello', ['aa', 'cc'], {'wahaha': '123'})
3. 可以写位置参数
def test(x,y): #这里是形参数 print(x) print(y) test(1,2) #这里是实参数 1 2
上面的test(y=2,x=1) 与顺序没有关系是关键字调用,上面是位置调用一一对应上面的,这样也可以 test(x=1,2) 不可以 text(1,y=2) 可以,只要满足都对应就行。关键参数不能写在位置参数前面。
4.局部变量 程序开始顶级的就是全局变量在全局生效,函数里面是局部变量
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = "tao" sex = 1 def change_name(name): global sex #声明修改全局变量 sex = 0 print('改变前:',name) name='TAO' age = 66 #这个变量局部的,出了函数就没有了 print('改变后:',name) #print('age',age) 这个age找不到 name = 'tao' change_name(name) print('外面的:',name) print(sex) # 改变前: tao # 改变后: TAO # 外面的: tao 发现只改变了函数里面的 外面的没有变化,全局就是在外面定义的变量顶头写的 ###列表和字典,类是可以在局部修改全部的就字符和数字是不可以改的
5.参数组 就是实参数不确定的时候怎么表达这就是参数组
##参数组的例子 *加变量名 最好名字叫 args 规范 def test(*args): #接受那个位置参数 print(args) test(1,2,3,4,6,8) #(1, 2, 3, 4, 6, 8) 变成了元组 def test1(*args1): print(args1) test1(*[1,2,3,4,6,8,9]) # args1 == [1,2,3,4,6,8,9] def test3(a,*args2): print(a) print(args2) test3(1,2,3,4) #也可以这么传参数 不确定多少参数的时候就会这么用 ###传递字典 **kwargs 把n个关键参数 def test4(**kwargs): #接受n个关键字参数 print(kwargs) test4(name='aa',age=99,sex='0') {'age': 99, 'name': 'aa', 'sex': '0'} #结果 def test5(**kwargs1): print(kwargs1) print(kwargs1['name']) #这样把字典里面的找出来了 test5(**{'name':'aa','age':99}) # {'name': 'aa', 'age': 99} # aa
6.函数的递归
# def calc(n): # print(n) # return calc(n+1) # calc(0) ##最后达到程序的最大递归限制999次停止 ##递归必须有一个明确的结束条件,每次进入更深入一层相比上一次要规模变小点,递归效率不高,层次过多就会导出溢出 ####一个小的递归 def calc1(a): print(a) if int(a/2) > 0: return calc1(int(a/2)) print(">>>",a) calc1(20) # 20 # 10 # 5 # 2 # 1 # >>> 1 只有不大于0后在执行后面的print
7.高阶函数:把函数作为参数传入,这样的函数称为高阶函数,函数式编程就是指这种高度抽象的编程范式
##高阶函数 def add(d,g,f): return f(d)+f(f) res = add (3,-6,abs) print(res) #abs 是个内置函数,取绝对值的意思, 函数调用函数
浙公网安备 33010602011771号