python - python文件名清理
问题描述
在 python 中是否可以去除所有特殊字符和空格并用连字符替换但保留点扩展名(即文件扩展名,例如 .mp4 或 .mov 或 .txt 或 .jpg 或 .png 或 .pdf)
例如:
string = 'Special $#! characters spaces_ 888323.mp4'
应该导致
Special-characters-spaces_-888323.mp4
我正在使用以下方法,但认为它不是正确的方法
re.sub('(\W+)','-', string).replace('-mp4','.mp4').replace('-mov','.mov')
解决方案
If it's really file names you're dealing with, consider using os.path.splitext
to temporarily detach the extension:
name, ext = os.path.splitext(string)
Now you can freely operate on name
, keeping ext
intact:
name = re.sub('(\W+)','-', name)
And then you just recombine:
string = name + ext
If it bothers you that this isn't a one-liner, make it into a function. I would also recommend pre-compiling the regex.
推荐阅读
- c - 在 Visual Studio 2017 中初始化可变大小的二维数组
- python - 光线多处理中的存储空间不足?
- javascript - Flask Socket-IO - 实时聊天应用程序,套接字无法正常工作
- node.js - 从后端获取图像并将其发送给客户端
- rapids - 用火花跑急流时 nvvp 时间线中的间隙
- c# - 尝试设置 SignalR 时找不到 UseSignalR 或 UseEndpoints
- c - 为什么我不能在纯 C 中包含 AppKit,即使我可以自己声明函数?
- yaml - 在 Azure DevOps 上使用 YAML 有条件地声明变量组
- python - 从 .egg-info 名称中去除 python 版本
- javascript - 未在 react-native 中显示关键错误,创建自己的组件时