• day 19 typing模块、re模块、爬虫、collections模块


     typing模块

      typing模块: 提供了Generator,Iterable,Iterator三种数据类型,限制函数输入输出的数据类型

    def self_add(x: int, y: int):  pycharm自带了优化
    return x + y

    from typing import Generator,Iterable,Iterator

    # 参数的数据类型 返回值
    def func(i: int, f: float, b: bool, lt: list, tup: tuple, dic: dict,g:Generator) -> tuple:
    lis = [i, f, b, lt, tup, dic]
    return tuple(lis)

    # i, f, b, lt, tup, dic = func(1,2,3,4,5,6) # 不错误,只是不规范,但是之后的引用可能会报错
    def ger():
    yield

    res = func(1, 2, True, [1, 2], (1, 2), {'a': 1},ger())
    print(res)


    re模块
    re模块: 从字符串里找特定的字符串

    re的基本语法(匹配规则):

    import re
    s = '王大炮打炮被大炮打死了 王大炮打炮被大炮打死了'
    0 1 2 3 4 5 6 7 8 9 10
    print(s[1:3], s[6:8])
    res = re.findall('大.',s)
    print(res) #['大炮', '大炮', '大炮', '大炮']

    # ^: 开头
    print(re.findall('^王大炮', s)) # ['王大炮']
    # $: 结尾
    print(re.findall('死了$', s)) # ['死了']
    # []: 匹配中间的字符,只要单个字符
    s = 'acefghjkacefsdfsdf'
    print(re.findall('[acef]', s)) # 只要单个字符
    # []+^联用: ^对[]内的元素取反
    print(re.findall('[^acef]', s))
    # .: 任意字符(除了 )
    s = 'abacadaeaf'
    print(re.findall('a..', s))

    s = 'abaacaaaaa'
    # *: 前面的字符0-无穷个
    print(re.findall('a*', s))
    # +: 前面的字符1-无穷个
    print(re.findall('a+', s))
    # ?: 前面的字符0-1个
    print(re.findall('a?', s))
    # {m}: 前面的字符m个
    print(re.findall('a{5}', s))
    # {n,m}: 前面的字符2-3个 # 'abaacaaaaa'
    # a aa aaa aa
    print(re.findall('a{2,5}', s))

    # d: 数字
    s = 's 1 s+ =$ 2_s 3'
    print(re.findall('d', s))
    # D: 非数字
    print(re.findall('D', s))
    # w: 数字/字母/下划线
    print(re.findall('w', s))
    # W: 非数字/字母/下划线
    print(re.findall('W', s))
    # s: 空格/ /
    print(re.findall('s', s))
    # S: 非空格/ /
    print(re.findall('S', s))

    # : 取消意义
    s = 'abad'
    print(re.findall(r'a\d', s))

    # .*: 贪婪模式(最大化),找到继续找,让结果最大化
    s = 'abbbcabc'
    print(re.findall('a.*c', s))

    # .*?: 非贪婪模式(最小化),找到就马上停止
    print(re.findall('a.*?c', s))

    # (): 只要括号内的
    s = 'abacad'
    print(re.findall('a(.)', s))

    # A|B: A和B都要
    s = 'abacad'
    print(re.findall('a|b', s))


    re模块的方法


    # re.compile
    '''
    修饰符 描述
    re.I 使匹配对大小写不敏感
    re.L 做本地化识别(locale-aware)匹配
    re.M 多行匹配,影响 ^ 和 $
    re.S 使 . 匹配包括换行在内的所有字符
    re.U 根据Unicode字符集解析字符。这个标志影响 w, W, , B.
    re.X 该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。
    '''
    s = 'abc123 def456'
    # print(re.findall('d+',s))
    # com = re.compile('d+')
    par = 'd+'
    # com = re.compile('3.',re.S)
    # print(re.findall(com, s))
    print(re.findall('3.', s, re.S))


    # re.findall()
    s = '123abc123 def456'
    # print(re.findall('d+', s))

    # re.mathch() 搜索开头,搜索到了就有,没搜索到就是none
    # res = re.match('d+', s)
    # print(res)
    # print(res.group())

    # re.search() 搜索第一个匹配结果,找到了就不找了
    # res = re.search('d+', s)
    # print(res)
    # print(res.group())

    # re.split(): 按照匹配规则切割
    s1 = 'abc324asdfk234lkjsf324lkj'
    print(re.split('d+', s1))

    # re.sub(): 按照匹配规则替换(**********)
    print(re.sub('d+', '***', s1))

    # re.subn(): 按照匹配规则替换,并计数
    print(re.subn('d+', '***', s1))

    # 分组: 一个括号里的叫一个分组, django, 了解
    s = 'abc123edf456'
    res = re.search('abc(?P<abc>d+)edf(?P<edf>d+)', s)
    print(res.groupdict())


    爬虫
    import re
    import os
    import requests
    'http://www.xiaohuar.com/list-2-8.html'
    for i in range(1,9):
    url = f'http://www.xiaohuar.com/list-2-{i}.html'

    res = requests.get(url)
    data = res.text

    res = re.findall('src="(.*?.jpg)"', data)
    for i in res: # type:str
    if i.startswith('/d/file'):
    i = f'http://www.xiaohuar.com{i}'

    img_name = i.split('/')[-1]
    img_path = os.path.join('img', img_name)
    res = requests.get(i)
    img_content = res.content # 针对图片/视频/音频需要用content
    with open(img_path, 'wb') as fw:
    fw.write(img_content)
    fw.flush()
    print(f'下载图片{img_name}成功')


    collections模块
    collections模块: 复杂的数据类型
    # 有名的元组
    from collections import namedtuple
    point = namedtuple('point',['x','y'])
    p = point(1,2)
    print(p.x)
    print(p.y)

    # 默认字典
    from collections import defaultdict
    # dic = {'a':1}
    # print(dic['b'])
    dic = defaultdict(lambda :'nan') # dic = {} # 如果找不到赋了一个默认值
    dic['a'] = 1
    print(dic['a'])
    print(dic['c'])


    # 双端队列
    # lis = [1,2,3] # 线性表
    # lis.append(4)
    # print(lis)
    from collections import deque # 链表

    de = deque([1,2,3])
    de.append(4)
    print(de)
    de.appendleft(0)
    print(de)
    de.popleft()
    de.popleft()
    print(de)


    # 计数器
    from collections import Counter
    s= 'programming'

    # dic = {}
    # for i in s:
    # if i in dic:
    # dic[i]+=1
    # else:
    # dic[i] =1
    # print(dic)

    c = Counter() # 字典
    for i in s:
    c[i] +=1
    print(c)






  • 相关阅读:
    被遗忘的Ruby Web开发框架
    批处理设置IP地址
    Java集合类ArrayList,Vector,HashMap,Hashtable区别
    eclipse安装Eclipse HTML Editor插件
    安装MYSQL向导时,到最后一步 Mysql server instance configuration wizard 单击完成时没反响应?
    各种缓存综述
    linux下apache字符集问题
    ubuntu下图形界面软件问题综述
    linux1xh3c802.11在ubuntu下联网
    REMOTE_ADDR,HTTP_CLIENT_IP,HTTP_X_FORWARDED_FOR
  • 原文地址:https://www.cnblogs.com/wwei4332/p/11382865.html
Copyright © 2020-2023  润新知