在内置数据类型(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'
正则表达式 : 从一大堆字符串中,找出你想要的字符串,在于对你想要得这个字符串进行一个精确地描述,与爬虫息息相关,方法非常多,匹配规则
什么是正则
正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。(在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模块)
原文:https://www.cnblogs.com/chenshuo531702820/p/11142034.html