【Python爬虫与数据分析】进阶语法

目录

一、异常捕获

二、迭代器

三、拆包、聚合、映射

[四、filter() 函数](#四、filter() 函数)

五、匿名函数

六、闭包

七、装饰器


一、异常捕获

异常捕获可增强程序的健壮性,即程序在遇到遇到异常的时候并不会做中断处理,而是会将异常抛出,由程序员来分析异常和做异常处理。

python 复制代码
a = 1
b = '2'
 
try:
    print('运算开始')    # 执行
    print(a + b)
except Exception as e:
    print('运行报错')    # 执行
    print(e)            
else:
    print('未出现异常')  # 未执行
finally:
    print('运行完毕')    # 执行

二、迭代器

迭代器通常用于数据结构对象的遍历,可以通过for循环 控制或者next()函数 控制,next()函数中可以添加防报错提示,防止next()越界访问。

python 复制代码
# 1 2 3 4 这四个数字可以组成多少个各个位数不同的数字
count = 0
_list = [1, 2, 3, 4]
for i in _list:
    for j in _list:
        for k in _list:
            for l in _list:
                # 利用集合的特性
                if len({i, j, k, l}) == 4:
                    sum = i * 1000 + j * 100 + k * 10 + l
                    print(sum, end=' ')
                    count += 1
print(f'\ncount = {count}')

x = 'python'
y = iter(x)
print(y)    # <str_iterator object at 0x0000016D5FF99A80>
print(next(y, '已经迭代结束了'))   # p, 在next函数中的字符串,便是防报错提示
print(next(y, '已经迭代结束了'))   # y
print(next(y, '已经迭代结束了'))   # t
print(next(y, '已经迭代结束了'))   # h
print(next(y, '已经迭代结束了'))   # o
print(next(y, '已经迭代结束了'))   # n
print(next(y, '已经迭代结束了'))   # 已经迭代结束了
print(next(y, '已经迭代结束了'))   # 已经迭代结束了
print(next(y, '已经迭代结束了'))   # 已经迭代结束了

三、拆包、聚合、映射

python 复制代码
# 拆包
i, j, k, l = [1, 2, 3, 4]
print(i, end=" ")
print(j, end=" ")
print(k, end=" ")
print(l)    # 1 2 3 4

# 聚合, 短板效应
x = [1, 2]
y = [1, 2, 3]
z = ['hello', 'world', '!']
print(zip(x, y, z))     # <zip object at 0x000001E496F37500>
for e in zip(x, y, z):
    print(e, end=" ")   # (1, 1, 'hello') (2, 2, 'world') 32 9 100
print()

# 映射,短板效应
x = [2, 3, 10, 2]
y = [5, 2, 2]
a = map(pow, x, y)  # pow()幂函数,pow(2, 5), pow(3, 2), pow(10, 2)
print(a)            # <map object at 0x000001B45AC2ADA0>
for e in a:
    print(e, end=" ")   # 32 9 100

四、filter() 函数

filter() 函数从数据结构对象obj中筛选出符合某个函数func()条件的数据

filter() 函数会根据所提供的func()函数可迭代对象obj的每个元素进行遍历,将遍历时的运算结果为真的元素,以迭代器的形式返回

python 复制代码
def Even(n):
    return n % 2 == 0
 
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = list(filter(Even, a))
print(b)    # [2, 4, 6, 8, 10]

五、匿名函数

在Python语言中除了def语句用来定义函数 之外,还可以使用匿名函数 lambda,它是Python一种生成函数对象的表达式形式。

  • 匿名函数通常是创建了可以被调用的函数,它返回了函数,而并没有将这个函数命名。
  • 普通函数需要去依靠函数名去调用,而匿名函数没有,所以需要把这个函数对象复制给某个变量进行调用
  • lambda有时被叫做匿名函数也就是这个原因,需要一个函数,又不想动脑筋去想名字,这就是匿名函数。
  • 匿名函数的 : 冒号前面的变量是形参,冒号后面的变量是返回值,返回值后面可以加条件判断语句对返回值做选择
cpp 复制代码
func = lambda x, y : x + y
print(func(2, 5))   # 7
 
func = lambda x : x if x % 2 == 0 else None
print(func(4))      # 4
print(func(5))      # None

六、闭包

闭包函数的必要条件

  • 闭包函数必须返回一个函数对象
  • 闭包函数返回的那个函数必须引用外部变量(一般不能是全局变量),而返回的那个函数内部不一定要return
python 复制代码
def func():
    name = 'python'
    def inner():
        print('hello world')
        return name
    return inner
 
f = func()
f()     # hello world
 
print(f())
# hello world
# python

用闭包实现日志记录程序

python 复制代码
import logging
def log_header(logger_name):
    logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(name)s] %(levelname)s  %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
    logger = logging.getLogger(logger_name)
 
    def _logging(something, level):
        if level == 'debug':
            logger.debug(something)
        elif level == 'warning':
            logger.warning(something)
        elif level == 'error':
            logger.error(something)
        else:
            raise Exception("I dont know what you want to do?" )
    return _logging
 
project_1_logging = log_header('project_1')
project_2_logging = log_header('project_2')
 
def project_1():
    #do something
    project_1_logging('this is a debug info', 'debug')
    #do something
    project_1_logging('this is a warning info', 'warning')
    # do something
    project_1_logging('this is a error info', 'error')
 
def project_2():
    # do something
    project_2_logging('this is a debug info', 'debug')
    # do something
    project_2_logging('this is a warning info', 'warning')
    # do something
    project_2_logging('this is a critical info', 'error')
 
project_1()
project_2()
python 复制代码
#输出
2018-05-26 22:56:23 [project_1] DEBUG  this is a debug info
2018-05-26 22:56:23 [project_1] WARNING  this is a warning info
2018-05-26 22:56:23 [project_1] ERROR  this is a error info
2018-05-26 22:56:23 [project_2] DEBUG  this is a debug info
2018-05-26 22:56:23 [project_2] WARNING  this is a warning info
2018-05-26 22:56:23 [project_2] ERROR  this is a critical info

七、装饰器

闭包:本质也是函数,参数和返回值都是函数,对函数进行增强

语法糖:没有增强新功能,对语言没有影响,更方便程序员使用

python 复制代码
import time


def CountTimeWrapper(func):
    # 闭包
    def ImproveFunc(*args, **kwargs):  # 增强函数应该把接收到的参数传给原函数
        start_time = time.perf_counter()
        ret = func(*args, **kwargs)  # 传入参数并记录返回值
        end_time = time.perf_counter()
        print(f'函数的执行时间为{end_time - start_time}')
        return ret

    return ImproveFunc


@CountTimeWrapper  # @闭包函数名,就是装饰器,自增强一次
def PrintOdds(lim=100):
    cnt = 0
    for i in range(lim):
        if i % 2 == 0:
            cnt += 1
    return cnt


if __name__ == '__main__':
    # PrintOdds = CountTimeWrapper(PrintOdds)
    # 装饰器等价于在第一次调用时执行上面语句
    print(PrintOdds())  # 打印程序运行时间和计算结果
相关推荐
小李不困还能学几秒前
PyCharm下载安装与配置教程
ide·python·pycharm
博观而约取厚积而薄发10 分钟前
Pytest 从入门到精通,一篇就够(超详细实战教程)
python·测试工具·单元测试·自动化·pytest
imzed20 分钟前
使用 Playwright + Pytest 构建 Web UI 自动化测试框架
python·自动化·pytest
普通网友25 分钟前
pytest一些常见的插件
开发语言·python·pytest
时空系34 分钟前
Python 高性能高压缩打包器 —— 基于 JianPy 语义分析引擎
python
cndes1 小时前
给Miniconda换源,让包下载更迅速
开发语言·python
Metaphor6921 小时前
使用 Python 添加、隐藏和删除 PDF 图层
python·pdf·图层
丨白色风车丨1 小时前
【Python 计算机视觉】基于 Dlib+OpenCV 实现实时人眼疲劳检测(闭眼预警)
python·opencv·计算机视觉
嘘嘘出差1 小时前
从零到精通:爬虫技术进阶路线全解析
爬虫