Python笔记(三):集合、文件、字符编码

本节主要记录集合文件以及字符编码块。


集合

如果一个元素同时存在多个列表中,集合可以很方便的去重关系测试

去重

列表list中存在重复元素,可以将其转换成集合:

list = [1,5,9,6,5,7,5,4]
list = set(list)
print(list, type(list))

>>{1,4,5,6,7,9} class<'set'> #变成大括号,像字典但不是(集合是无序的)

关系测试

  • 两个集合交集、并集、差集、子集和反向差集
list1 = set([1,5,9,6,5,7,5,4])
list2 = set([2,4,5,7,2,0,11,16])
print(list1.intersection(list2))    #交集
>>{4,5,7}

print(list1.union(list2))           #并集
>>{0,1,2,4,5,6,7,9,11,16}        

print(list1.difference(list2))         #差集    (我这有,你那没有)
>>{1,6,9}             list1中有,list2中没有的

list3 = set([1,5,9])
print(lsit3.issubset(list1))           #子集
>>True

print(list1.insuperset(list3))      #父集
>>True

print(list1.symmetric_difference(list2))    #反向差集
>>{0,1,2,6,9.11.16}
#即:去掉都有的(取出两个互相没有的合在一起)

lsit4 = set([4,6,8])
print(list3.isdisjoint(list4))     #检测是否有重,没有为真
>>True

还有更为简单的编写方式:

#交集
print(list1 & list2)

#并集
print(list2 | list1)

#差集
print(list1 - list2)    #在1中不在2中

#对称差集
print(list1 ^ list2)
  • 集合的 增、删、改、查
#增
list.add()        #增加一项
list.update([10,66,89])

#删
list.pop()        #随机删
list.remove(10)
list.discard(10)      #当删除元素不存在时,remove报错,discard不报错

#查

文件

对文件操作流程:
- 1、打开文件,得到文件句柄并复制给一个变量
- 2、通过句柄对文件进行操作
- 3、关闭文件

文件的基本操作

首先创建一个名为iron的文本

注意事项:
- 文件句柄:存放了文件的字符集、大小以及在硬盘上的起始位置。
- 文件打开时都要说明是读(”r”)还是写(”w”)或者是追加(”a”)
- 写模式将创建一个新的文件,会覆盖已有的文件,需特别注意!!

  • 读、写、追加
#读
f = open("iron","r",encoding = "utf-8")     #文件句柄
data = f.read()
data2 = f.read()      #data2取不到值,因为前面操作已经将光标走至末尾了
print(data)

#写
f = open("iron2","w",encoding = "utf-8")
f.write("面朝大海\n")
f.write("春暖花开\n")

#追加
f = open("iron2","a",encoding = "utf-8")
f.write("我有一所房子\n")

f.close()
  • 想实现逐行读取内容,或者读到某一行做个记号
f.open("iron2","r",encoding = "utf-8")
print(f.readline())       #读一行
print(f.readlines())     #读取所有的内容,换行输出为\n

for line in f.readlines():
    print(line.strip())        #strip 去掉所有的换行

#使用读取单行来获得整个内容
f = open("iron","r",encoding = "utf-8")
count = 0
for line in f:
    if count == 9:
        print("\t----------下面是第十行---------")
        count += 1
        continue
    print(line)
    count += 1

#在第十行插入分割行
  • 读取文件后,将光标移回去
f = open("iron","r",encoding = "utf-8")
print(f.tell())             #从文件句柄处,指针所在的位置
print(f.read(5))
print(f.tell())

>> 0
>> 《刺客信条
>> 15                    读了5个位,每个占3字节

f.seek(0)       #回到开头
  • 进度条
import sys,time

for i in range(20)
    sys.stdout.write("#")
    sys.stdout.flush()    #没有此句则将在内存里逐个刷新,然后统一显示
    time.sleep(0.2)      #0.2s显示一个
  • 修改
#读写      r+  —— 先读,再写

f = open("iron","r+","utf-8")         

print(f.readline())
print(f.tell())                 #显示当前光标所在位置

f.write("----------------")

>> 《刺客信条:启示录》
>> 32           #第一行到30,第二行开头有两个空格,所以32


#写读      w+         先写(创建新文件)再读

f = open("iron","w+",encoding="utf-8")


#修改内容
f = open("iron","r",encoding="utf-8")
f_new = open("iron2","w",encoding="utf-8")
for line in f:
    if "独行刺客" in line:
        line = line.replace("独行刺客""黑夜杀手")   
    f_new.write(line)     #独行刺客替换为黑夜杀手,继续写入新文件中
f.close()
f_new.close()
  • 以其他类型打开
#以二进制--读       rb      (网络传输必须用二进制模式)

f = open("iron","rb")        #不用指定编码格式了(二进制嘛)
print(f.readline())

>>b'\xe3\x80\x8a\xe5\x88\xba\xe5\xae\xa2\xe4\xbf\xa1\xe6\x9d\xa1\xef\xbc\x9a\xe5\x90\xaf\xe7\xa4\xba\xe5\xbd\x95\xe3\x80\x8b\r\n'
>开头b表示是bytes类型

#以二进制--写      wb
f = open("iron","wb")
f.write("hello\n".encode())      #不填默认utf-8
f.close()

>>Hello

自动关闭文件,防止忘记关闭占用内存:

#使用with语句

with open("iron","r",encoding="utf-8") as f ,\
        open("iron2","r",encoding="utf-8") as f2:
    for line in f:
        print(line)
#同时打开多个文件  ,\   单行不能太长

字符编码

不同编码之间相互转换,可以以Unicode为中间量
x → Unicode → y
decode → Unicode → encode

扫描二维码关注公众号,回复: 938027 查看本文章
#-*- coding:gbk -*-      首先声明程序该文件使用gbk编码(只是文件)

import sys
print(sys.getfilesystemencoding())
>> utf-8                        

s = "你好"          #这个是个unicode编码(python默认unicode编码)

print(s)
print(s.encode("gbk"))     #encode成gbk编码
print(s.encode("utf-8"))        #encode成utf-8编码
print(s.encode("utf-8".decode("utf-8".encode("gb2312")))
#先转成utf-8编码,然后decode(写当前编码类型),然后在转成gb2312


decode 不用指明类型,因为 decode 是转成 unicode 类型

附录

iron

《刺客信条:启示录》
  Deep in the ocean, dead and cast away.深海之处,一片死寂。
  Where innocence's burn in flames.无辜生命,烈焰吞噬。
  A million mile from home, I'm walking ahead.背井离乡,渐行渐远。
  I'm frozen to the bones, I am...彻骨寒冷,我是……
  A soldier on my own, I don't know the way.独行刺客,行无目的。
  I'm riding up the heights of shame.独步飞乘,耻辱之巅。
  I'm waiting for the call, the hand on the chest.诚待召唤,胸前执手。
  I'm ready for the fight, and fate....准备一战,命运……
  The sound of iron shocks is stuck in my head.金戈声声,冲击脑海。
  The thunder of the drums dictates.战鼓阵阵,指引心路。
  The rhythm of the falls, the number of dead's.山倒之律,死尸一片。
  The rising of the horns, ahead....号角之音,前方……
  From the dawn of time to the end of days.亡灵序曲,末世浩劫。
  I will have to run away,身不由己,奔走江湖。
  I want to feel the pain and the bitter taste.心经痛彻,体悟苦涩。
  Of the blood on my lips, again....嘴角鲜血,再次……
  This deadly burst of snow is burning my hands.雪烈肃杀,烧红吾手。
  I'm frozen to the bones, I am...彻骨寒冷,而我……
  A million mile from home, I'm walking away.背井离乡,默默离开。
  I can't remind your eyes, your face.我已遗忘,你的双眼,你的脸庞

猜你喜欢

转载自blog.csdn.net/weixin_42026630/article/details/80355737