文章目录
斜杆问题
- windows 的路径一般用两个倒斜杠 \ ,为什么要用两个\,因为要做转义
- linux 的路径一般用斜杠 /
os 模块
- os.getcwd() 获取当前工作路径
- os.chdir(path) 更改当前工作路径
- os.makedirs(package_name) 创建新文件夹
- os.path.join() 将字符串连接成路径
正则表达式
- Python 中所有正则表达式的函数都在 re 模块中
- 用 compile() 传入一个字符串值,表示正则表达式,它返回一个 Regex 模式对象
- Regex 对象的 search() 方法查找传入的字符串,寻找该正则表达式的所有匹配。如果没有,返回 None
1. 正则简单使用
- compile() 先编译,看有没有语法错误
- 在compile() 中传入第二个参数 re.I 可以忽略大小写,如
re.compile(r'robocop', re.I)
- search() 和 match() 的区别,search 会查找整个字符串,match 只匹配当前
- r 表示匹配原字符串,加上 r 可以省略转义字符
import re
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d{4}')
mo = phoneNumRegex.search('My number is 415-555-4242.Another phone number is 123-456-7890')
print('phone number found: ' + mo.group())
输出
phone number found: 415-555-4242
2. match()、search()、findall()、finditer()区别
2.1 match()
从首字母开始匹配,string如果包含pattern子串,则匹配成功,返回Match对象,失败则返回None,若要完全匹配,pattern要以$结尾。
import re
rule = re.compile('aaa')
result_1 = rule.match('aaab')
result_2 = rule.match('baaa')
print(result_1)
print(result_2)
输出
<re.Match object; span=(0, 3), match=‘aaa’>
None
2.2 search()
若string中包含pattern子串,则返回Match对象,否则返回None,注意,如果string中存在多个pattern子串,只返回第一个。
import re
rule = re.compile('aaa')
result_1 = rule.search('aaab')
result_2 = rule.search('baaa')
print(result_1)
print(result_2)
输出
<re.Match object; span=(0, 3), match=‘aaa’>
<re.Match object; span=(1, 4), match=‘aaa’>
2.3 findall()
返回string中所有与pattern相匹配的全部字串,返回形式为数组。
import re
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d{4}')
mo = phoneNumRegex.findall('My number is 415-555-4242.Another phone number is 123-456-7890')
print(mo)
输出
[‘415-555-4242’, ‘123-456-7890’]
2.4 finditer()
返回string中所有与pattern相匹配的全部字串,返回形式为迭代器。
import re
result = re.finditer(r'a+', 'aaabaaaaa')
print(result)
输出
<callable_iterator object at 0x0000023C3651D940>
3. 常见符号
符号 | 含义 |
---|---|
| | 匹配多个分组(或) |
* | 匹配零次或多次 |
+ | 匹配一次或多次 |
{次数a} | 匹配 a 次 |
4. 常用字符分类的缩写
符号分类 | 表示 |
---|---|
\d | 0 到 9 的任何数字 |
\D | 除 0 到 9 的数字以外的任何字符 |
\w | 任何字母、数字或下划线字符(可以认为是匹配“单词”字符) |
\W | 除字母、数字和下划线以外的任何字符 |
\s | 空格、制表符或换行符(可以认为是匹配“空白”字符) |
\S | 除空格、制表符或换行符以外的任何字符 |
[] | 匹配某个范围的内容,[0-5]只匹配数字 0 到 5 |
^ | 表示非 |
注意:
- 在方括号内,不需要加上斜杠转义 .*?() 这些字符
5. 要点总结
- ?匹配零次或一次前面的分组。
- *匹配零次或多次前面的分组。
- +匹配一次或多次前面的分组。
- {n}匹配n 次前面的分组。
- {n, }匹配n 次或更多前面的分组。
- {,m}匹配零次到m 次前面的分组。
- {n, m}匹配至少n 次、至多m 次前面的分组。
- {n, m}?或*?或+?对前面的分组进行非贪心匹配。
- ^spam 意味着字符串必须以spam 开始。
- spam$意味着字符串必须以spam 结束。
- .匹配所有字符,换行符除外。
- \d、\w 和\s 分别匹配数字、单词和空格。
- \D、\W 和\S 分别匹配出数字、单词和空格外的所有字符。
- [abc]匹配方括号内的任意字符(诸如a、b 或c)。
- [^abc]匹配不在方括号内的任意字符。