【Python】Python工具包
本文内容根据【 菜鸟教程·python3 正则表达式】整理得到。
正则匹配re(regular expression)
使用方法
:使用正则匹配需要引用模块re。
import re
re.search和re.match函数
功能
:
- 使用re.search函数从输入string中任意位置搜索给定模板类型。
- 使用re.match函数从输入string的开头匹配给定模板类型。
函数形式
:
import re
# search string based on regular expression.
matchObj = re.search(pattern, string, flags = 0)
matchObj = re.match(pattern, string, flags = 0)
参数解释
:
参数 | 解释 |
---|---|
pattern | 匹配的正则表达式 |
string | 被匹配的输入字符串 |
flags | 用于控制正则表达式的匹配方式 |
返回值
:匹配成功返回匹配对象,否则返回None。
获取匹配值
:在模板中使用括号()提取目标匹配元素,并通过group()函数获取目标元素的值。
import re
matchLine = re.search(r"^(\w+)\s+\d+x\d+\s+(\d+)\s+\d+\s+(\d+)", line)
matchedItem1 = matchLine.group(1)
matchedItem2 = matchLine.group(2)
数学工具math
from math import ceil
常用函数
# Function: return a new list containing all items from the iterable in ascending order.
# Arguments: 1) A custom key function can be supplied to customize the sort order. 2) The reverse flag can be set to request the result in descending order.
sorted(iterable, /, *, key=None, reverse=False)
# Function: return an object that produces a sequence of integers from start to stop by step. If start is not present, start from 0 by default.
i = range(start, stop[, step])
待分类
from os.path import exists
# check whether the file exists.
if not exists(pathLog):