一、Python相关
1、正则表达式
(1)正则表达式基础
①含义:记录文本规则的代码。
②注意:需要导入re模块
③特点:
- 语法比较复杂,可读性较差。
- 通用性很强,适用于多种编程语言
④步骤:
- 导入re模块
- 使用match方法进行匹配操作,re.match()能匹配出以xxx开头的字符串,如果起始位置没有匹配成功,返回None
- 如果上一步数据匹配成功,使用group()提取数据。
①普通字符
直接匹配字符本身:
-
a
匹配字母a
-
5
匹配数字5
②特殊字符(需转义)
使用 \
转义特殊字符:
-
\.
匹配.
(如example.com
中的点) -
\\
匹配\
③字符集合
-
[abc]
匹配a
、b
或c
中的任意一个字符。 -
[a-z]
匹配任意小写字母。 -
[^abc]
匹配非a
、b
、c
的字符(取反)。
④ 预定义字符类
-
\d
匹配数字(等价于[0-9]
)。 -
\D匹配非数字。
-
\w
匹配字母、数字或下划线(等价于[a-zA-Z0-9_]
)。 -
\W匹配非单词字符。
-
\s
匹配空白字符(空格、制表符、换行等)。 -
\S匹配非空白。
-
.
匹配任意字符(默认不包括换行符,使用re.DOTALL
标志可包含)。
示例:
import re
# 匹配单个数字
re.findall(r'\d', "a1b2c3") # ['1', '2', '3']
# 匹配非字母字符
re.findall(r'[^a-zA-Z]', "a1!b2@") # ['1', '!', '2', '@']
(2)正则表达式高级用法
匹配多个内容:通过量词控制匹配的次数。
量词:
-
*
:0次或多次(贪婪模式)。 -
+
:1次或多次。 -
?
:0次或1次。 -
{m}:匹配前一个字符出现m次。
-
{m,n}
:匹配前一个字符出现
至少m
次,至多n
次(如{3}
表示精确匹配3次)。
①贪婪与非贪婪模式
贪婪模式(默认):.* (尽可能多匹配)
re.findall(r'a.*b', 'a123b456b') # ['a123b456b']
非贪婪模式:.*? (尽可能少匹配)
re.findall(r'a.*?b', 'a123b456b') # ['a123b', 'a456b']
示例:
# 匹配连续3个数字
re.findall(r'\d{3}', "12345") # ['123', '45'](第二个匹配不满足3位)
# 匹配1到3个字母
re.findall(r'[a-z]{1,3}', "abc def") # ['abc', 'def']
import re
text = "<div>content1</div><div>content2</div>"
# 贪婪匹配(匹配整个字符串)
re.findall(r'<div>.*</div>', text) # ['<div>content1</div><div>content2</div>']
# 非贪婪匹配(匹配单个div标签)
re.findall(r'<div>.*?</div>', text) # ['<div>content1</div>', '<div>content2</div>']
②匹配开头与结尾
-
^ 匹配字符串开头(或在多行模式
re.MULTILINE
下匹配行首)。 -
$ 匹配字符串结尾(或在多行模式下匹配行尾)。
-
\A
严格匹配字符串开头。 -
\Z
严格匹配字符串结尾
示例:
# 匹配以 "http" 开头的字符串
re.findall(r'^http', "http://example.com") # ['http']
# 匹配以 ".com" 结尾的字符串
re.findall(r'\.com$', "example.com") # ['.com']
# 多行模式匹配每行开头
text = "Line1\nLine2"
re.findall(r'^Line', text, flags=re.MULTILINE) # ['Line', 'Line']
③分组匹配与反向引用
捕获组 ( )
-
用
()
包裹内容,捕获匹配的子字符串。 -
通过
\1
、\2
反向引用分组(或在替换时使用$1
、$2
)。
示例:
# 匹配日期格式(年-月-日)
text = "2023-10-05"
match = re.search(r'(\d{4})-(\d{2})-(\d{2})', text)
print(match.groups()) # ('2023', '10', '05')
print(match.group(1)) # '2023'
# 替换日期格式为 "月/日/年"
re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', text) # '10/05/2023'
非捕获组 (?: )
- 仅分组但不捕获(节省内存,提高性能)。
re.findall(r'(?:https?|ftp)://([^/]+)', "http://example.com ftp://test.org")
# 匹配域名:['example.com', 'test.org']
命名分组 (?P<name> )
- 通过名称引用分组,提高可读性。
match = re.search(r'(?P<year>\d{4})-(?P<month>\d{2})', "2023-10")
print(match.group('year')) # '2023'
print(match.groupdict()) # {'year': '2023', 'month': '10'}
示例:
# 分组提取
match = re.search(r'(\d{3})-(\d{4})', 'Phone: 123-4567')
print(match.group(1)) # '123'
# 反向引用(匹配重复单词)
re.findall(r'\b(\w+)\b\s+\1', 'hello hello world') # ['hello']
④预搜索(零宽断言)
# 正向肯定预查(匹配后面是 '@' 的字符)
re.findall(r'\w+(?=@)', 'user@example.com') # ['user']
(3)综合示例
匹配邮箱
email_pattern = r'^[\w.-]+@[\w-]+(\.[\w-]+)+$'
emails = "user@example.com, invalid@.com"
re.findall(email_pattern, emails, flags=re.MULTILINE) # ['user@example.com']
匹配重复单词
text = "hello hello world"
re.findall(r'\b(\w+)\b\s+\1', text) # ['hello'](匹配连续重复的单词)
总结
-
单个字符:字符集合、预定义字符类。
-
多个内容:量词控制次数,注意贪婪与非贪婪模式。
-
开头结尾:
^
和$
控制边界。 -
分组匹配:捕获组、非捕获组、命名分组的灵活使用。
2、高级用法
2.1、re.search():扫描整个字符串并返回第一个成功匹配的对象,如果匹配失败,则返回None。
示例:
import re
text = "Order ID: ABC123, Date: 2023-10-05"
# 提取第一个订单ID和日期
match = re.search(r'Order ID: (\w+), Date: (\d{4}-\d{2}-\d{2})', text)
if match:
print("完整匹配:", match.group(0)) # Order ID: ABC123, Date: 2023-10-05
print("订单ID:", match.group(1)) # ABC123
print("日期:", match.group(2)) # 2023-10-05
print("所有分组:", match.groups()) # ('ABC123', '2023-10-05')
关键方法:
-
group(0)
:返回完整匹配的字符串。 -
group(n)
:返回第n
个分组的匹配内容。 -
groups()
:返回所有分组的元组。 -
groupdict()
:返回命名分组的字典(需使用(?P<name>...)
语法)。
2.2、re.match():仅从字符串开头匹配。
-
功能:仅在字符串开头检查匹配,若开头不匹配则返回
None
。 -
与
re.search()
的区别:match()
只在开头匹配,search()
搜索整个字符串。
示例:
text = "2023-10-05 is a date"
match = re.match(r'\d{4}-\d{2}-\d{2}', text)
if match:
print("匹配到的日期:", match.group()) # 2023-10-05
text2 = "Today is 2023-10-05"
match2 = re.match(r'\d{4}-\d{2}-\d{2}', text2)
print(match2) # None(因为日期不在开头)
2.3、re.findall():以列表形式返回整个字符串中所有匹配到的字符串。
-
功能:返回字符串中所有非重叠匹配项的列表(直接返回字符串,而非
Match
对象)。 -
分组行为:若正则中有分组,返回分组内容的元组列表。
示例:
text = "Emails: user1@example.com, user2@test.org"
# 提取所有邮箱
emails = re.findall(r'\b[\w.-]+@[\w.-]+\.\w+\b', text)
print(emails) # ['user1@example.com', 'user2@test.org']
# 提取邮箱的用户名和域名(分组)
email_parts = re.findall(r'(\w+)@([\w.-]+\.\w+)', text)
print(email_parts) # [('user1', 'example.com'), ('user2', 'test.org')]
2.4、re.sub():将匹配到的数据进行替换。
-
功能:将匹配的内容替换为指定字符串或函数返回值。
-
分组引用:在替换字符串中使用
\1
、\2
引用分组。
示例:
text = "2023-10-05 和 2024-12-31"
# 将日期格式从 "年-月-日" 改为 "月/日/年"
new_text = re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', text)
print(new_text) # 10/05/2023 和 12/31/2024
# 使用函数动态替换(将数字加1)
def increment_year(match):
year = int(match.group(1)) + 1
return f"{year}-{match.group(2)}-{match.group(3)}"
new_text = re.sub(r'(\d{4})-(\d{2})-(\d{2})', increment_year, text)
print(new_text) # 2024-10-05 和 2025-12-31
2.5、re.split():根据匹配进行切割字符串,并返回一个列表。
-
功能:根据正则表达式分割字符串,返回列表。
-
保留分隔符:若正则中包含分组,分隔符也会包含在结果中。
示例:
text = "苹果, 香蕉; 西瓜|芒果"
# 按逗号、分号或竖线分割
parts = re.split(r'[,;|]\s*', text)
print(parts) # ['苹果', '香蕉', '西瓜', '芒果']
# 包含分隔符(使用分组)
parts_with_delim = re.split(r'([,;|])\s*', text)
print(parts_with_delim) # ['苹果', ',', '香蕉', ';', '西瓜', '|', '芒果']
2.6、re.finditer():返回所有匹配的迭代器。
-
功能:返回一个迭代器,包含所有匹配的
Match
对象。 -
优势:适用于处理大文本时节省内存。
示例:
text = "IPs: 192.168.1.1, 10.0.0.1"
# 提取所有IP地址及其各部分
for match in re.finditer(r'(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})', text):
print("完整IP:", match.group(0))
print("四个部分:", match.groups())
2.7、re.compile():预编译正则表达式。
-
功能:将正则表达式编译为
Pattern
对象,提高重复使用时的效率。 -
优势:适用于多次使用同一正则的场景。
示例:
import re
# 预编译正则表达式
date_pattern = re.compile(r'(\d{4})-(\d{2})-(\d{2})')
text1 = "日期: 2023-10-05"
text2 = "截止时间: 2024-12-31"
# 复用编译后的正则
match1 = date_pattern.search(text1)
match2 = date_pattern.search(text2)
print(match1.groups()) # ('2023', '10', '05')
print(match2.groups()) # ('2024', '12', '31')
标志参数(Flags)
-
常用标志:
-
re.IGNORECASE
(re.I
):忽略大小写。 -
re.MULTILINE
(re.M
):多行模式(^
和$
匹配每行的开头结尾)。 -
re.DOTALL
(re.S
):.
匹配包括换行符在内的所有字符。
-
示例:
text = "Hello\nWorld"
# 多行模式匹配行首
matches = re.findall(r'^\w+', text, flags=re.MULTILINE)
print(matches) # ['Hello', 'World']
# 忽略大小写匹配
match = re.search(r'world', text, flags=re.IGNORECASE)
print(match.group()) # World
总结
-
re.search()
:查找第一个匹配项,适合提取关键信息。 -
re.findall()
:快速获取所有匹配的文本列表。 -
re.sub()
:灵活替换文本内容(支持函数回调)。 -
re.compile()
:提升性能,代码更简洁。 -
分组和标志:增强正则表达式的灵活性和精确性。
通过组合这些方法,可以高效处理文本解析、数据清洗、日志分析等复杂任务。
3、常用模块
(1)OS模块
作用:用于和操作系统进行交互
通用操作:
- 获取平台信息。
- 对目录的操作
- 判断操作
os.name:指示正在使用的工作平台(返回操作系统类型:对于Windows,返回nt。对于Linux,返回posix.)
os.getenv(环境变量名称):读取环境变量。
- os.path.split():把目录名和文件名分离,以元组的形式接收,第一个元素是目录路径,第二个元素是文件名。
- os.path.dirname:显示split分割的第一个元素,即目录。
- os.path.basename:显示split分割的第二个元素,即文件名。
- os.path.isfile:判断是否存在文件。
- os.path.isdir:判断目录是否存在。
# 导入模块
import os
# 目录操作
os.mkdir("new_dir") # 创建目录
os.rmdir("new_dir") # 删除空目录
os.listdir(".") # 列出当前目录内容
os.rename("old", "new") # 重命名
os.walk("/path") # 递归遍历目录
# 路径操作
os.path.join("dir", "file.txt") # 拼接路径
os.path.abspath("file.txt") # 绝对路径
os.path.exists("file.txt") # 检查存在性
(2)sys模块
作用:负责程序跟Python解释器的交互。
- sys.getdefaultencoding():获取系统默认编码格式。
- sys.path:获取环境变量的路径,跟解释器相关。
- sys.platform:获取操作系统平台名称。
- sys.version:获取Python解释器的版本信息。
import sys
sys.argv # 命令行参数列表
sys.exit(0) # 退出程序
sys.path.append("/custom/module/path") # 添加模块搜索路径
sys.stdin/sys.stdout/sys.stderr # 标准输入/输出/错误流
(3)time模块
time.sleep():延时操作,以秒为单位。
import time
time.sleep(2) # 暂停2秒
current_time = time.time() # 时间戳(秒)
local_time = time.localtime() # 结构化时间
formatted = time.strftime("%Y-%m-%d %H:%M:%S", local_time) # 格式化时间
(4)logging模块
logging.basicConfig() 配置root logger的参数。
filename:指定日志文件的文件名,所有会显示的日志都会存放到这个文件。
filemode:文件的打开方式,默认是a,追加模式。
level:指定日志显示级别,默认是警告信息warning。
format:指定日志信息的输出格式。
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
filename='app.log'
)
logger = logging.getLogger(__name__)
logger.info("This is an info message")
(5)random模块
作用:用于实现各种分布的伪随机数生成器,可以根据不同的实数分布来随机生成值。
random.random():产生大于0且小于1之间的小数。
random.uniform(a,b):产生指定范围的随机小数。
random.randint(a,b):产生a,b范围内的随机整数,包含开头和结尾。
random.randrange(start,stop,[step]):产生start,stop范围内的整数,包含开头不包含结尾。
import random
random.randint(1, 10) # 1-10的随机整数
random.choice(["a", "b", "c"]) # 随机选择元素
random.shuffle([1,2,3]) # 打乱列表顺序
二、Linux系统命令
1、虚拟机管理
安装虚拟机工具
# 安装VirtualBox
sudo apt install virtualbox
# 使用Vagrant创建虚拟机
vagrant init ubuntu/focal64 && vagrant up
关机与重启
shutdown -h now # 立即关机
shutdown -r +5 # 5分钟后重启
reboot # 立即重启
2、目录操作
cd /path # 切换目录
ls -l # 详细列表
mkdir dir # 创建目录
rmdir dir # 删除空目录
pwd # 显示当前路径
tree # 树形显示目录结构
3、文件操作
touch file.txt # 创建空文件
cp src.txt dest # 复制文件
mv old.txt new.txt # 移动/重命名
rm file.txt # 删除文件(谨慎使用 -r 递归删除)
cat file.txt # 查看文件内容
head -n 5 file # 显示前5行
tail -f log.txt # 实时跟踪日志
4、压缩文件操作
# tar打包
tar -cvf archive.tar dir/ # 创建tar包
tar -xvf archive.tar # 解压tar包
# gzip压缩
gzip file.txt # 压缩为.gz
gunzip file.txt.gz # 解压.gz
# zip压缩
zip -r archive.zip dir/ # 压缩为zip
unzip archive.zip # 解压zip
5、其他常用命令
# 查找文件
find /path -name "*.txt" # 按名称查找
grep "pattern" file.txt # 搜索文本
# 进程管理
ps aux | grep python # 查看进程
kill -9 PID # 强制终止进程
# 网络相关
ping google.com # 测试网络连通性
ifconfig # 查看网络接口