18.Python略有小成(collections模块,re模块)
Python(collections模块,re模块)
一、collections模块
在内置数据类型(dict、list、set、tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter、deque、defaultdict、namedtuple和OrderedDict等。
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'])
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()
,这样就可以非常高效地往头部添加或删除元素。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})
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']
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模块
正则表达式 : 从一大堆字符串中,找出你想要的字符串,在于对你想要得这个字符串进行一个精确地描述,与爬虫息息相关,方法非常多,匹配规则
什么是正则
正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。(在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。 () 匹配括号内的表达式,也表示一个组 匹配模式举例
# ----------------匹配模式-------------------- # 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']命名分组举例(了解)
# 命名分组匹配:
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模块)的更多相关文章
- Python 常用模块(1) -- collections模块,time模块,random模块,os模块,sys模块
主要内容: 一. 模块的简单认识 二. collections模块 三. time时间模块 四. random模块 五. os模块 六. sys模块 一. 模块的简单认识 模块: 模块就是把装有特定功 ...
- Python内置模块(re+collections+time等模块)
Python内置模块(re+collections+time等模块) 1. re模块 import re 在python要想使用正则必须借助于模块 re就是其中之一 1.1 findall功能( re ...
- Python中collections模块
目录 Python中collections模块 Counter defaultdict OrderedDict namedtuple deque ChainMap Python中collections ...
- Python的collections模块中namedtuple结构使用示例
namedtuple顾名思义,就是名字+元组的数据结构,下面就来看一下Python的collections模块中namedtuple结构使用示例 namedtuple 就是命名的 tuple,比较 ...
- python:collections模块
Counter类 介绍:A counter tool is provided to support convenient and rapid tallies 构造:class collections. ...
- python之collections模块(OrderDict,defaultdict)
前言: import collections print([name for name in dir(collections) if not name.startswith("_" ...
- Python模块02/序列化/os模块/sys模块/haslib加密/collections
Python模块02/序列化/os模块/sys模块/haslib加密/collections 内容大纲 1.序列化 2.os模块 3.sys模块 4.haslib加密 5.collections 1. ...
- oldboy edu python full stack s22 day16 模块 random time datetime os sys hashlib collections
今日内容笔记和代码: https://github.com/libo-sober/LearnPython/tree/master/day13 昨日内容回顾 自定义模块 模块的两种执行方式 __name ...
- 转载:Python中collections模块
转载自:Python中collections模块 目录 Python中collections模块 Counter defaultdict OrderedDict namedtuple deque Ch ...
随机推荐
- 用OKR提升员工的执行力
很多管理者在公司管控的过程中常常出现一种乏力的感觉,觉得很多事情推进不下去,结果总是令人不满意.管理者总是会吐槽,“员工执行力差!”而此时大部分管理者会认为公司执行力差是员工能力和态度的问题. 事实上 ...
- 1-移远GSM/GPRS M26 模块 Mini板 开发板(使用说明)
板子预览 引脚说明 供电 关于串口电压匹配引脚: 上面一版朋友测试反应的问题 (上面的内容不删除,因为已经出售了1套) 1,源码开发完以后,烧录完成 PWRKEY按键不能使用了,需要断电上电,那么就需 ...
- BZOJ 3435: [Wc2014]紫荆花之恋
二次联通门 : BZOJ 3435: [Wc2014]紫荆花之恋 二次联通门 : luogu P3920 [WC2014]紫荆花之恋 /* luogu P3920 [WC2014]紫荆花之恋 怀疑人生 ...
- 初识es
初识es es是什么? es是基于Apache Lucene的开源分布式(全文)搜索引擎,,提供简单的RESTful API来隐藏Lucene的复杂性. es除了全文搜索引擎之外,还可以这样描述它: ...
- 第12组 Beta版本演示
前言 组长博客 组名: To Be Done 组员和贡献比例 短学号 姓名 分工 贡献比例 614 王永福* 前后端实现.发任务.催进度 30% 440 孙承恺 UI设计 15% 529 邱畅杰 文本 ...
- Dubbo+zookeeper实现单表的增删改查
1.数据库准备 建表语句 CREATE TABLE `tb_brand` ( `id` ) NOT NULL AUTO_INCREMENT, `name` ) DEFAULT NULL COMMENT ...
- 手把手实例对比String、StringBuilder字符串的连接效率及StringBuilder和StringBuffer线程安全的比较
一.字符串连接的效率问题 使用String连接字符串时为什么慢? 小知识点 java中对数组进行初始化后,该数组所占的内存空间.数组长度都是不可变的. 创建一个字符串,为字符串对象分配内存空间,会耗费 ...
- [LINUX] 快速回收连接
i /etc/sysctl.conf 编辑文件,加入以下内容:net.ipv4.tcp_syncookies = 1net.ipv4.tcp_tw_reuse = 1net.ipv4.tcp_tw_r ...
- OpenSSL的证书, 私钥和签名请求(CSRs)
概述 OpenSSL是一个多用途的工具, 适用于涉及Public Key Infrastructure(PKI), HTTPS(HTTP over TLS)的用途. 这份文档提供关于OpenSSL命令 ...
- gmake: Nothing to be done for `all'.
安装gc_buffercache的时候报错: [root@~ pg_buffercache]# gmake gmake: Nothing to be done for `all'. 解决方法: > ...