使用正则表达式模块“re”遇到的错误

源代码:
python 复制代码
model_dir = re.split("\checkpoints\", args.model_path)[0]

上面的代码中,我想要将args.model_path中checkpoints之前的部分提取出来,比如args.model_path="D:\Vscode\GitHub_Code\TPRO-main\work_dirs\luad\classification\checkpoints\mit_b0.pth",则model_dir="D:\Vscode\GitHub_Code\TPRO-main\work_dirs\luad\classification\"。

遇到的错误:
python 复制代码
re.error: bad escape \c at position 0
原因:

正则表达式中使用了 \c,但 \c 不是一个有效的转义序列,因此会引发错误。

解决措施:
python 复制代码
方法一:
model_dir = re.split("\\checkpoints\\", args.model_path)[0]
即使用"\\"代替"\"

方法二:
model_dir = re.split(r"\\checkpoints\\", args.model_path)[0]
即使用"\\\\"代替"\",同时使用了原始字符串(raw string) r 前缀,以确保正则表达式引擎能够正确解释

注意:本人使用的是Windows系统,如果是Linux系统应该不会出现这个问题。

相关推荐
安大小万10 小时前
VSCode的json文件不允许注释的解决办法
ide·vscode·编辑器
拉不拉斯12 小时前
vsCode远程连接Centos 7出现的错误以及解决办法
ide·vscode·centos
wild-civil12 小时前
解决Keil 生成的文件在 VSCode 乱码问题(自动识别,不用手动改编码)
ide·vscode·stm32·编辑器
freewlt1 天前
Cline v3.82.0 发布:VS Code AI编程助手迎来重大更新
vscode·cline
HealthScience1 天前
vscode使用Excel插件导致codex插件无法粘贴图片
服务器·vscode·excel
霜落花轻扬1 天前
VSCode全局搜索内容不全
ide·vscode·编辑器
棒棒的唐1 天前
配置 VSCode 的 PHP Intelephense 插件,去掉因php版本不同导至的红色波浪线误判
ide·vscode·php
努力的小帅1 天前
Ubuntu 使用 avahi/mDNS 实现固定连接(VSCode Remote SSH + NoMachine)
linux·vscode·ubuntu·ssh·linux入门
十年之少1 天前
使用VSCode 对PyQt5 say Hello—— Python + Qt 开发
vscode·python·qt
MuYiLuck1 天前
02-VSCode插件与Trae原生AI编辑器实战教程
vscode·编辑器·trae·trae solo