爬虫 学习笔记(2) Python(容器,文件读写,异常处理,logging,多线程,)

  1. 代码格式
  2. 关键字
  3. 基本语法
  4. 容器与字符串
  5. 函数
  6. 面向对象
  7. 文件读写
  8. 多线程
  9. 错误与异常

关键字(key word)

  • 常量:True False None
  • 对象与容器:class import from del
  • 逻辑操作:and or not
  • 函数:def return
  • 判断与循环控制:if elif else is assert while
    **for ** 只作用于容器
    continue 结束本次迭代进入下一个
    break:中断整个循环
  • 异常:raise try except finally
    with as
  • 作用域: global nonlocal
  • 匿名函数:yield lambda

容器(for 只作用于容器)

  1. list

#添加元素
#append and extend!!!
li=[0]
li.append([1,2,3])
#[0, [1, 2, 3]]
li_2=[1,2,3]
li.extend(li_2)
#[0, [1, 2, 3], 1, 2, 3]

#删除元素
li.pop()  #删除最后一个,带参数的话删除所处位置的元素

# 排序
li.sort() #从小到大

  
  1. tuple:只读list
  2. set:没有重复的list
  3. dict:字典(哈希表)
  4. 数组切片

li = [1,2,3,4,5]
li[0:3]   #1,2,3
li[-1,-4,-1]  #5,4,3 

#!!!!li_0_2[-1] =100
print(li)  #[1,2,3,4,5] 切边是复制,不改变原数组
  1. 字符串与数组的关系!!!
    不能修改字符串,应该先把字符串变成list,再修改
#修改字符串
s='asdfdfgh'
li =list(s)
s=''.join(list)
print(s)

s="-"join(li)
print(s) #用-连接起来

#!!!!切割
s='qaz,wsx,edc'
p1,p2,p3 = s.split(',')
print(p1,p2,p3)

面向对象

  1. type()查看对象类型
  2. dir查看对象属性和方法
  3. dir
class Clazz(Object):
    #self 类比C++的this 指针
    def __init__(self,x,y):
        self.x=x
        self.y=y
    # 申明成员函数时,第一个参数需为self
    def display(self):
        print(self.x,self.y)
print(type(Clazz))
clz = Clazz(100,200)
clz = display() #==>display(clz) 
# 继承
class Base:
    def run(self):
       print('Base::run')
class Tom(Base):
    def run(self):
        print('Tom::run')
t=Tom()
t.run()

文件读写

  1. 文本文件读写
f = open('','r')
# r-read, w,rw, w+判断是否存在,存在的话删了重来

#读取小文件
for line in f.readlines():
    print(line)
  1. 二进制文件读写

  2. string 与bytes

  3. 文件和目录操作

错误和异常处理

  1. logging库使用
  • logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等;相比print,具备如下优点:
  • 可以通过设置不同的日志等级,在release版本中只输出重要信息,而不必显示大量的调试信息;
  • print将所有信息都输出到标准输出中,严重影响开发者从标准输出中查看其它数据;logging则可以由开发者决定将信息输出到什么地方,以及怎么输出;
    实现将不同的等级的信息写到不同的日志文件里在实际生产中经常得到应用
 logging.info(...)
 logging.debug(...)
  1. with as
#
with open("text.txt") as f
    for line in f.readlines():
        print(line)
class Sample(object):             # object类是所有类最终都会继承的类    
    def __enter__(self):          
        print("In __enter__()")
        return "Foo"   
                           
    def __exit__(self, type, value, trace):        
        print("In __exit__()")  

    def get_sample():    
        return Sample()  
with get_sample() as sample:
    print("sample:", sample) 

>>>In __enter__()
>>>sample: Foo
>>>In __exit__()
  • 首先我们调用get_sample()函数,返回Sample类
  • 执行Sample类中的__enter__()方法,打印"in__enter()"字符串,并将字符串“Foo”赋值给 as 后边的sample变量;
  • 执行with__block代码块,即打印"sample: %s"字符串,结果为“sample Foo”执行with__block代码块结束后,返回Sample()类,
  • 执行类方法__exit__().因为在执行with__block代码块时并没有错误返回,所以type,value,trace这三个argument都没有值,直接打印print"in__exit__()"

总之,记住with as 等价于

try:

    执行__enter__的内容

    执行 with_block

finally:
   执行__exit__内容
import logging

try:
   r=10/0
except ZeroDivisionErro as e:
   print(type(e))
   print(e)
finally:
   print('Always come here.')
#finally 一般用来关闭一些资源,防止资源泄露(服务端,本地端)

多线程threading

  1. 多线程
  2. 多进程
  3. 线程同步
  4. 多线程编程经验
    创建线程
import threading
# 执行函数
def thread_func(x):
   print("%d\n" %(x*1000))

threads=[]
for i in range(5):
   threads.append(threading.Thread(target = thread_func,args = (100, ))) #元组

for thread in threads:
   thread.start()
#等线程执行结束
for thread in threads:
   thread.join()
>>>10000
>>>10000
>>>10000
>>>10000
>>>10000
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值