用python把相同名称的放在一起_如何在python中将相似文件名的文件合并在一起?...

该博客介绍了如何使用Python处理包含连续数字的文件名。通过正则表达式匹配四位或以上数字,然后利用more_itertools库将连续数字分组,最后创建并打印新的格式化文件名列表。这种方法适用于需要对连续编号的文件进行批量操作的场景。
摘要由CSDN通过智能技术生成

You can do as follows. Start with matching numbers with 4 or more digits, (the regex "\d{4,}" matches 4 or more digits) and extract all numbers. Then group consecutive numbers together using more_itertools.consecutive_groups, and create the result list, and then print it

import re

import os

from more_itertools import consecutive_groups

files = ["default.xml", "df_ak01.1001.jpg", "df_ak01.1002.jpg", "df_ak01.1003.jpg", "df_ak01.1005.jpg", "df_ak01.1006.jpg"]

#Pattern to match numbers with 4 or more digits

pattern = re.compile("\d{4,}")

#Extract all numbers

a = [int(pattern.search(x).group(0)) for x in files if pattern.search(x)]

#[1001, 1002, 1003, 1005, 1006]

#Group consecutive numbers together

cons_groups = [list(group) for group in consecutive_groups(a)]

#[[1001, 1002, 1003], [1005, 1006]]

#Create result list

result = [ [len(x), '{}-{}'.format(x[0], x[-1])] for x in cons_groups]

#[[3, '1001-1003'], [2, '1005-1006']]

#Print the result list

for item in result:

print('{} df_ak01.%04d.jpg {}'.format(item[0], item[1]))

输出将是

3 df_ak01.%04d.jpg 1001-1003

2 df_ak01.%04d.jpg 1005-1006

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值