Python(collections模块,re模块)

一、collections模块

在内置数据类型(dict、list、set、tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter、deque、defaultdict、namedtuple和OrderedDict等。

  1. namedtuple: 生成可以使用名字来访问元素内容的tuple

    我们知道tuple可以表示不变集合,例如,一个点的二维坐标就可以表示成:

    >>> p = (1, 2)

    但是,看到(1, 2),很难看出这个tuple是用来表示一个坐标的。

    这时,namedtuple就派上了用场:

    >>> from collections import namedtuple
    >>> Point = namedtuple('Point', ['x', 'y'])
    >>> p = Point(1, 2)
    >>> p.x
    1
    >>> p.y
    2

    类似的,如果要用坐标和半径表示一个圆,也可以用namedtuple定义:

    #namedtuple('名称', [属性list]):
    Circle = namedtuple('Circle', ['x', 'y', 'r'])
  2. deque: 双端队列,可以快速的从另外一侧追加和推出对象

    使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储,数据量大的时候,插入和删除效率很低。

    deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈:

    >>> from collections import deque
    >>> q = deque(['a', 'b', 'c'])
    >>> q.append('x')
    >>> q.appendleft('y')
    >>> q
    deque(['y', 'a', 'b', 'c', 'x'])

    deque除了实现list的append()pop()外,还支持appendleft()popleft(),这样就可以非常高效地往头部添加或删除元素。

  3. Counter: 计数器,主要用来计数

    Counter类的目的是用来跟踪值出现的次数。它是一个无序的容器类型,以字典的键值对形式存储,其中元素作为key,其计数作为value。计数值可以是任意的Interger(包括0和负数)。Counter类和其他语言的bags或multisets很相似。

    c = Counter('abcdeabcdabcaba')
    print c
    输出:Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
  4. OrderedDict: 有序字典

    使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。

    如果要保持Key的顺序,可以用OrderedDict

    >>> from collections import OrderedDict
    >>> d = dict([('a', 1), ('b', 2), ('c', 3)])
    >>> d # dict的Key是无序的
    {'a': 1, 'c': 3, 'b': 2}
    >>> od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
    >>> od # OrderedDict的Key是有序的
    OrderedDict([('a', 1), ('b', 2), ('c', 3)])

    注意,OrderedDict的Key会按照插入的顺序排列,不是Key本身排序:

    >>> od = OrderedDict()
    >>> od['z'] = 1
    >>> od['y'] = 2
    >>> od['x'] = 3
    >>> od.keys() # 按照插入的Key的顺序返回
    ['z', 'y', 'x']
  5. defaultdict: 带有默认值的字典

    有如下值集合[11,22,33,44,55,66,77,88,99,90...],将所有大于66的值保存至字典的第一个key中,将小于66的值保存至第二个key的值中。

    即: {'k1': 大于66, 'k2': 小于66}

    li = [11,22,33,44,55,77,88,99,90]
    result = {}
    for row in li:
    if row > 66:
    if 'key1' not in result:
    result['key1'] = []
    result['key1'].append(row)
    else:
    if 'key2' not in result:
    result['key2'] = []
    result['key2'].append(row)
    print(result)
    from collections import defaultdict
    values = [11, 22, 33,44,55,66,77,88,99,90]
    my_dict = defaultdict(list)
    for value in values:
    if value>66:
    my_dict['k1'].append(value)
    else:
    my_dict['k2'].append(value)

    使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict

    >>> from collections import defaultdict
    >>> dd = defaultdict(lambda: 'N/A')
    >>> dd['key1'] = 'abc'
    >>> dd['key1'] # key1存在
    'abc'
    >>> dd['key2'] # key2不存在,返回默认值
    'N/A'

二、re模块

正则表达式 : 从一大堆字符串中,找出你想要的字符串,在于对你想要得这个字符串进行一个精确地描述,与爬虫息息相关,方法非常多,匹配规则

  1. 什么是正则

    正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。(在Python中)它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。

    元字符 匹配内容
    \w 匹配字母(包含中文)或数字或下划线
    \W 匹配非字母(包含中文)或数字或下划线
    \s 匹配任意的空白符
    \S 匹配任意非空白符
    \d 匹配数字
    \D p匹配非数字
    \A 从字符串开头匹配
    \z 匹配字符串的结束,如果是换行,只匹配到换行前的结果
    \n 匹配一个换行符
    \t 匹配一个制表符
    ^ 匹配字符串的开始
    $ 匹配字符串的结尾
    . 匹配任意字符,除了换行符,当re.DOTALL标记被指定时,则可以匹配包括换行符的任意字符。
    [...] 匹配字符组中的字符
    [^...] 匹配除了字符组中的字符的所有字符
    * 匹配0个或者多个左边的字符。
    + 匹配一个或者多个左边的字符。
    匹配0个或者1个左边的字符,非贪婪方式。
    {n} 精准匹配n个前面的表达式。
    {n,m} 匹配n到m次由前面的正则表达式定义的片段,贪婪方式
    a|b 匹配a或者b。
    () 匹配括号内的表达式,也表示一个组
  2. 匹配模式举例

    # ----------------匹配模式--------------------
    
    # 1,之前学过的字符串的常用操作:一对一匹配
    # s1 = 'fdskahf九阳神功'
    # print(s1.find('九阳')) # 7 # 2,正则匹配: # 单个字符匹配
    import re
    # \w 与 \W
    # \w 匹配,数字,字母下划线,中文
    # \W 匹配除了小\w能匹配的其他剩余符号
    # print(re.findall('\w', '九阳sg 12*() _')) # ['九', '阳', 's', 'g', '1', '2', '_']
    # print(re.findall('\W', '九阳sg 12*() _')) # [' ', '*', '(', ')', ' '] # \s 与\S
    # \s 匹配的空格,\t,\n
    # \S 匹配除了\s的其它
    # print(re.findall('\s','九阳sg*(_ \t \n')) # [' ', '\t', ' ', '\n']
    # print(re.findall('\S','九阳shengong*(_ \t \n')) # ['九', '阳', 's', 'g', '*', '(', '_'] # \d 与 \D
    # \d 匹配的是数字,同时制作规则可以指定,\d\d ['12','23'...]
    # \D 匹配除了\d的其它
    # print(re.findall('\d','1234567890 shen *(_')) # ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
    # print(re.findall('\D','1234567890 shen *(_')) # [' ', 's', 'h', 'e', 'n', ' ', '*', '(', '_'] # \A 与 ^ 匹配规则相同,从开头匹配,相同就拿出来不同就[]
    # print(re.findall('\Ahel','hello 九阳神功 -_- 666')) # ['hel']
    # print(re.findall('^hel','hello 九阳神功 -_- 666')) # ['hel'] # \Z 与 $ 匹配规则相同,从结尾匹配,相同就拿出来不同就[]
    # print(re.findall('666\Z','hello 九阳神功 *-_-* \n666')) # ['666']
    # print(re.findall('666$','hello 九阳神功 *-_-* \n666')) # ['666'] # \n 与 \t
    # \n 匹配换行符
    # \t 匹配制表符
    # print(re.findall('\n','hello \n 九阳神功 \t*-_-*\t \n666')) # ['\n', '\n']
    # print(re.findall('\t','hello \n 九阳神功 \t*-_-*\t \n666')) # ['\t', '\t'] # 重复匹配
    # 元字符匹配
    # . ? * + {m,n} .* .*? # . 匹配任意一个字符,如果匹配成功光标则移到匹配成功的字符后,未成功光标则正常移动,除了换行符(re.DOTALL 这个参数可以匹配\n)。
    # print(re.findall('a.b', 'ab aab a*b a2b a九b a\nb')) # ['aab', 'a*b', 'a2b', 'a九b']
    # print(re.findall('a.b', 'ab aab a*b a2b a九b a\nb',re.DOTALL)) # ['aab', 'a*b', 'a2b', 'a九b'] # ?匹配0个或者1个由左边的字符定义的片段
    # print(re.findall('a?b', 'ab aab abb aaaab a九b aba**b')) # ['ab', 'ab', 'ab', 'b', 'ab', 'b', 'ab', 'b'] # * 匹配0个或者多个左边字符表达式。 满足贪婪匹配
    # print(re.findall('a*b', 'ab aab aaab abbb')) # ['ab', 'aab', 'aaab', 'ab', 'b', 'b']
    # print(re.findall('ab*', 'ab aab aaab abbbbb')) # ['ab', 'a', 'ab', 'a', 'a', 'ab', 'abbbbb'] # + 匹配1个或者多个左边字符表达式。 满足贪婪匹配
    # print(re.findall('a+b', 'ab aab aaab abbb')) # ['ab', 'aab', 'aaab', 'ab'] # {m,n} 匹配m个至n个左边字符表达式 满足贪婪匹配
    # print(re.findall('a{2,4}b', 'ab aab aaab aaaaabb')) # ['aab', 'aaab'] # .* 贪婪匹配 从头到尾,遇到换行符\n会断掉
    # print(re.findall('a.*b', 'ab aab a*()b')) # ['ab aab a*()b'] # .*? 此时的?不是对左边的字符进行0次或者1次的匹配,
    # 而只是针对.*这种贪婪匹配的模式进行一种限定:告知他要遵从非贪婪匹配 推荐使用!
    # print(re.findall('a.*?b', 'ab a1b a*()b, aaaaaab')) # ['ab', 'a1b', 'a*()b'] # []: 可以放任意规则,但是一个中括号代表一个字符
    # - 在[]中表示范围,如果想要匹配上- 那么这个-符号不能放在中间.
    # ^ 在[]中表示取反的意思.
    # print(re.findall('a.b', 'a1b a3b aeb a*b arb a_b')) # ['a1b', 'a3b', 'a4b', 'a*b', 'arb', 'a_b']
    # print(re.findall('a[abc]b', 'aab abb acb adb afb a_b')) # ['aab', 'abb', 'acb']
    # print(re.findall('a[0-9]b', 'a1b a3b aeb a*b arb a_b')) # ['a1b', 'a3b']
    # print(re.findall('a[a-z]b', 'a1b a3b aeb a*b arb a_b')) # ['aeb', 'arb']
    # print(re.findall('a[a-zA-Z]b', 'aAb aWb aeb a*b arb a_b')) # ['aAb', 'aWb', 'aeb', 'arb']
    # print(re.findall('a[0-9][0-9]b', 'a11b a12b a34b a*b arb a_b')) # ['a11b', 'a12b', 'a34b']
    # print(re.findall('a[*-+]b','a-b a*b a+b a/b a6b')) # ['a*b', 'a+b']
    # - 在[]中表示范围,如果想要匹配上- 那么这个-符号不能放在中间.
    # print(re.findall('a[-*+]b','a-b a*b a+b a/b a6b')) # ['a-b', 'a*b', 'a+b']
    # print(re.findall('a[^a-z]b', 'acb adb a3b a*b')) # ['a3b', 'a*b'] # 分组: # () 制定一个规则,将满足规则的结果匹配出来
    # print(re.findall('(.*?)_b', 'al_b wu_b 热_b')) # ['al', ' wu', ' 热'] # 应用举例:
    # print(re.findall('href="(.*?)"','<a href="http://www.baidu.com">点击</a>'))#['http://www.baidu.com']
  3. 命名分组举例(了解)

    # 命名分组匹配:
    ret = re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>")
    # #还可以在分组中利用?<name>的形式给分组起名字
    # #获取的匹配结果可以直接用group('名字')拿到对应的值
    # print(ret.group('tag_name')) #结果 :h1
    # print(ret.group()) #结果 :<h1>hello</h1>
    #
    # ret = relx.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>")
    # #如果不给组起名字,也可以用\序号来找到对应的组,表示要找的内容和前面的组内容一致
    # #获取的匹配结果可以直接用group(序号)拿到对应的值
    # print(ret.group(1))
    # print(ret.group()) #结果 :<h1>hello</h1>

18.Python略有小成(collections模块,re模块)的更多相关文章

  1. Python 常用模块(1) -- collections模块,time模块,random模块,os模块,sys模块

    主要内容: 一. 模块的简单认识 二. collections模块 三. time时间模块 四. random模块 五. os模块 六. sys模块 一. 模块的简单认识 模块: 模块就是把装有特定功 ...

  2. Python内置模块(re+collections+time等模块)

    Python内置模块(re+collections+time等模块) 1. re模块 import re 在python要想使用正则必须借助于模块 re就是其中之一 1.1 findall功能( re ...

  3. Python中collections模块

    目录 Python中collections模块 Counter defaultdict OrderedDict namedtuple deque ChainMap Python中collections ...

  4. Python的collections模块中namedtuple结构使用示例

      namedtuple顾名思义,就是名字+元组的数据结构,下面就来看一下Python的collections模块中namedtuple结构使用示例 namedtuple 就是命名的 tuple,比较 ...

  5. python:collections模块

    Counter类 介绍:A counter tool is provided to support convenient and rapid tallies 构造:class collections. ...

  6. python之collections模块(OrderDict,defaultdict)

    前言: import collections print([name for name in dir(collections) if not name.startswith("_" ...

  7. Python模块02/序列化/os模块/sys模块/haslib加密/collections

    Python模块02/序列化/os模块/sys模块/haslib加密/collections 内容大纲 1.序列化 2.os模块 3.sys模块 4.haslib加密 5.collections 1. ...

  8. oldboy edu python full stack s22 day16 模块 random time datetime os sys hashlib collections

    今日内容笔记和代码: https://github.com/libo-sober/LearnPython/tree/master/day13 昨日内容回顾 自定义模块 模块的两种执行方式 __name ...

  9. 转载:Python中collections模块

    转载自:Python中collections模块 目录 Python中collections模块 Counter defaultdict OrderedDict namedtuple deque Ch ...

随机推荐

  1. 用TortoiseSVN从github下载单个文件

    问题描述: github是一个很好的共享代码管理仓库,我们可以从github上直接以压缩包的形式直接download整个项目,也可以通过git,用git clone + URL 命令下载整个目录. 但 ...

  2. learning java FileInputStream

    public class FileInputStreamTest { public static void main(String[] args) throws IOException { var f ...

  3. Win32下的中断和异常

    本文是Matt Pietrek在1997年月10月的MSJ杂志Under The Hood专栏上发表的文章.中断和异常在DOS时代是整个系统的灵魂,但Windows已将其隐藏到了系统深处.Matt P ...

  4. Chocolatey 方便的windows 包管理工具

    windows 在包管理上一般大家都是网上下载二进制文件或者就是通过软件管家进行安装,这些对于开发人员可能就有点不是 很专业了, Chocolatey 是一个不错的windows 软件包管理工具 安装 ...

  5. hasura skor 一个pg 的event trigger 扩展

    hasura skor 是一个hasura 团队早期的event triggerpg 扩展,新的推荐使用graphql engine 参考架构 缺点 只有在skor 运行的时候,数据才可以被捕捉处理 ...

  6. 2019qbxt游记

    Day 1 2019.8.6 来到qbxt的第一天,虽然早就对宾馆的等级做好了准备,但是还是十分的失望,外观是真的很简陋,不过里面还好的,,可以凑合. 我竟然和lbh一个宿舍!!!这次外出学习必将不安 ...

  7. matrix67中适合程序员的例子

    交互式证明:http://www.matrix67.com/blog/archives/6572 捡石子游戏(移动皇后问题):http://www.matrix67.com/blog/archives ...

  8. c博客作业—分支,结构顺序

    1展现PTA总分 1 2 2本章学习类容总结 1常量和变量 常量:在运行中其值不变的量被称为常量,常量的类型通常是由书写格式决定,包括整型常量,实数型变量等等. 变量: 在运行中其值可变的量被称为变量 ...

  9. 使用RedisDesktopManager客户端无法连接Redis服务器问题解决办法

    是否遇到安装完成后连不上的问题? 那么这篇教程能解决. 执行步骤: 1.修改redis文件夹下redis.cong文件,在bind 127.0.0.1行前面加#注释掉这一行,使能远程连接(默认只能使用 ...

  10. Websocket实现Java后台主动推送消息到前台

    写在前面 需求: 项目测试, 缺少用户登录失败给admin推送消息, 想到这个方式, 当用户登录失败时, admin用户会在页面看到咣咣乱弹的alert. 正文 pom.xml <!-- web ...