gpt4 book ai didi

python - 批处理文件重命名 : zero padding time with regex?

转载 作者:太空宇宙 更新时间:2023-11-04 00:08:58 24 4
gpt4 key购买 nike

我有一整套文件(超过 10.000 个),文件名中包含日期和时间。问题是日期和时间没有用零填充,导致排序出现问题。

文件名的格式为:output 5-11-2018 9h0m.xml
我想要的格式是:output 05-11-2018 09h00m.xml

我搜索过不同的解决方案,但大多数似乎都使用拆分字符串然后重新组合它们。这看起来很麻烦,因为在我的例子中,日、月、小时和分钟需要分开、填充然后重新组合。

我认为正则表达式可能会给我一些更好的解决方案,但我不太明白。

我根据 Wiktor Stribiżew 的建议编辑了我的原始代码,即您不能在替换中使用正则表达式,而是使用组:

import os
import glob
import re

old_format = 'output [1-9]-11-2018 [1-2]?[1-9]h[0-9]m.xml'
dir = r'D:\Gebruikers\<user>\Documents\datatest\'

old_pattern = re.compile(r'([1-9])-11-2018 ([1-2][1-9])h([0-9])m')

filelist = glob.glob(os.path.join(dir, old_format))
for file in filelist:
print file
newfile = re.sub(old_pattern, r'0\1-11-2018 \2h0\3m', file)
os.rename(file, newfile)

但这仍然无法完全按照我的意愿运行,因为它不会改变 10 点以下的小时数。我还能尝试什么?

最佳答案

您可以使用作为替换参数传递给 re.sub 方法的 lambda 表达式,用 .zfill(2) 填充文件名中的数字。

此外,修复正则表达式模式以允许 1 或 2 位数字:(3[01]|[12][0-9]|0?[1-9]) 对于日期, (2[0-3]|[10]?\d) 一个小时 (24h),([0-5]?[0-9])分钟:

old_pattern = re.compile(r'\b(3[01]|[12][0-9]|0?[1-9])-11-2018 (2[0-3]|[10]?\d)h([0-5]?[0-9])m')

参见 regex demo .

然后使用:

for file in filelist:
newfile = re.sub(old_pattern, lambda x: '{}-11-2018 {}h{}m'.format(x.group(1).zfill(2), x.group(2).zfill(2), x.group(3).zfill(2)), file)
os.rename(file, newfile)

参见 Python re.sub文档:

If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.

关于python - 批处理文件重命名 : zero padding time with regex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53152915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com