re 模块、typing 模块、collections 模块

时间:2019-08-23
本文章向大家介绍re 模块、typing 模块、collections 模块,主要包括re 模块、typing 模块、collections 模块使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、re 模块

1、导入方式

import re

2、作用

从字符串里找特定的字符串

3、基本语法

  • ^匹配开头

    s = 'abdhgtsab'
    print(re.findall('^abd',s))
    # ['abd']  开头有就输出abd,没有就回返回[]
  • $ 匹配结尾

    s = 'abdhgtsab'
    print(re.findall('ab$',s))
    
    # ['ab']  结尾有就返回ab,没有就返回[]
  • [] 匹配[]内的字符

    s = 'acefghjkacefsdfsdf'
    print(re.findall('[acef]', s))  # 只要[]内的单个字符
    -------------------------------------------------------------
    ['a', 'c', 'e', 'f', 'a', 'c', 'e', 'f', 'f', 'f']
  • ^[]对[]里面的元素取反,取出除了[]内的元素外的每个字符

    s = 'acefghjkacefsdfsdf'
    print(re.findall('[^acef]', s))
    ------------------------------------------------------
    ['g', 'h', 'j', 'k', 's', 'd', 's', 'd']
  • .任意字符(除了\n)

s = 'acefghjkacefsdfsdf'
print(re.findall('a..', s))
------------------------------------------------------
['aba', 'ada']
  • *前面的字符0-无穷个
s = 'abaacaaaaa'
print(re.findall('a*', s))
------------------------------------------------------
['a', '', 'aa', '', 'aaaaa', '']
  • +前面的字符1-无穷个
s = 'abaacaaaaa'
print(re.findall('a+', s))
------------------------------------------------------
['a', 'aa', 'aaaaa']
  • ?前面的字符0-1个
s = 'abaacaaaaa'
print(re.findall('a?', s))
------------------------------------------------------
['a', '', 'a', 'a', '', 'a', 'a', 'a', 'a', 'a', '']
  • {m}前面的字符m个
s = 'abaacaaaaa'
print(re.findall('a{5}', s))
------------------------------------------------------
['aaaaa']
  • {m,n}前面的字符m-n个
s = 'abaacaaaaa'
print(re.findall('a{2,5}', s))
------------------------------------------------------
['aa', 'aaaaa']
  • \d数字
s = 's  1   s+\n=$\t2_s  3'
print(re.findall('\d', s)
------------------------------------------------------
['1', '2', '3']
  • \D非数字
s = 's  1   s+\n=$\t2_s  3'
print(re.findall('\D', s)
------------------------------------------------------
['s', ' ', ' ', ' ', ' ', ' ', 's', '+', '\n', '=', '$', '\t', '_', 's', ' ', ' ']
  • \w数字/字母/下划线
s = 's  1   s+\n=$\t2_s  3'
print(re.findall('\w', s))
------------------------------------------------------
['s', '1', 's', '2', '_', 's', '3']
  • \W非数字/字母/下划线
s = 's  1   s+\n=$\t2_s  3'
print(re.findall('\W', s))
------------------------------------------------------
[' ', ' ', ' ', ' ', ' ', '+', '\n', '=', '$', '\t', ' ', ' ']
  • \s空格/\t/\n
s = 's  1   s+\n=$\t2_s  3'
print(re.findall('\s', s))
------------------------------------------------------
[' ', ' ', ' ', ' ', ' ', '\n', '\t', ' ', ' ']
  • \S非空格/\t/\n
s = 's  1   s+\n=$\t2_s  3'
print(re.findall('\S', s))
------------------------------------------------------
['s', '1', 's', '+', '=', '$', '2', '_', 's', '3']
  • \取消意义
s = 'aba\d'
print(re.findall(r'a\\d', s))
------------------------------------------------------
['a\\d']
  • .*贪婪模式(最大化),找到继续找,让结果最大化
s = 'abbbcabc'
print(re.findall('a.*c', s))
------------------------------------------------------
['abbbcabc']
  • .*?非贪婪模式(最小化),找到就马上停止
s = 'abbbcabc'
print(re.findall('a.*?c', s))
------------------------------------------------------
['abbbc', 'abc']
  • ()只要括号内的
s = 'abacad'
print(re.findall('a(.)', s))
------------------------------------------------------
['b', 'c', 'd']
  • A|B A和B都要
s = 'abacad'
print(re.findall('a|b', s))
------------------------------------------------------
['a', 'b', 'a', 'a']

4、模块方法

re.mathch(): 从开头搜索,搜索到了就有,没搜索到就是none

s = 'abc123\ndef456'
res = re.match('\d+', s)  #从开头搜索数字,搜索到了就有,没搜索到就是none 
print(res)
----------------------------------------------
None
s = '123abc123\ndef456'
res = re.match('\d+', s)
print(res)   #返回的是一个对象
print(res.group())  #对象必须用group()返回
-----------------------------------------------------
<re.Match object; span=(0, 3), match='123'>

re.search(): 搜索第一个匹配结果,找到了就不找了

s = '123abc123\ndef456'
res = re.search('\d+', s)
print(res)
print(res.group())
------------------------------------------------------
123

re.split(): 按照匹配规则切割

s1 = 'abc324asdfk234lkjsf324lkj'
print(re.split('\d+', s1))
-----------------------------------------------
['abc', 'asdfk', 'lkjsf', 'lkj']

re.sub(): 按照匹配规则替换(重点)

s1 = 'abc324asdfk234lkjsf324lkj'
print(re.sub('\d+', '***', s1))
-----------------------------------------------
abc***asdfk***lkjsf***lkj

re.subn(): 按照匹配规则替换,并计数

s1 = 'abc324asdfk234lkjsf324lkj'
print(re.subn('\d+', '***', s1))
-----------------------------------------------
('abc***asdfk***lkjsf***lkj', 3)

5、应用举例

例题:

​ 1.对于字符串Life234234is beautiful234because234of persistence

​ 2.请使用re模块 一行代码 还原这句话为Life is beautiful because of persistence

import re

s = 'Life234234is    beautiful234because234of    persistence'

# 结果为:Life is beautiful because of persistence

解答:

print(" ".join(re.sub('[0-9]', " ", s).split()))

二、typing 模块

1、导入方式

from typing import xxx

2、作用

提供生成器类型(cenerator),可迭代类型(iterable),迭代器类型(iterator)三种数据类型,限制函数

3、方法

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)
-----------------------------------------------------
(1, 2, True, [1, 2], (1, 2), {'a': 1})

三、collections 模块

1、导入方式

from collections import xxx

2、作用

用于复杂的数据类型

3、方法

3.1 有名元组 namedtuple

from collections import namedtuple
point = namedtuple('point',['x','y'])
p = point(1,2)
print(p.x)
print(p.y)
---------------------------------------------------
1
2

3.2 默认字典 defaultdict

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

3.3 双端队列

deque

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

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

# lis = [1,2,3]  # 线性表
# lis.append(4)   #在后面追加4
# print(lis)
from collections import deque  # 链表

de = deque([1,2,3])   
de.append(4)  #在最后面追加4
print(de)
de.appendleft(0)   #在最前面追加0
print(de)   # 默认删除左边的
de.popleft()
print(de)
-------------------------------------------------------------
deque([1, 2, 3, 4])

3.4 计数器

'''比较麻烦的方法'''
s= 'programming'
# dic = {}
# for i in s:
#     if i in dic:
#         dic[i]+=1
#     else:
#         dic[i] =1
# print(dic)
-------------------------------------------------------------
{'p': 1, 'r': 2, 'o': 1, 'g': 2, 'a': 1, 'm': 2, 'i': 1, 'n': 1}
# 新方法
from collections import Counter
s= 'programming'
c = Counter()  # 字典
for i in s:
    c[i] +=1   #在内部自己进行了一个判断
print(c)
-----------------------------------------------------
Counter({'r': 2, 'g': 2, 'm': 2, 'p': 1, 'o': 1, 'a': 1, 'i': 1, 'n': 1})

原文地址:https://www.cnblogs.com/zhuangyl23/p/11403001.html