空格下划线

发布时间 2023-10-31 13:37:14作者: 不上火星不改名
import os


def count_a(filename):
"""统计文件名中的a的数量,其中a是空格或下划线"""
return sum(1 for char in filename if char in ['_', ' '])


def parse_a_range(a_range):
"""解析a范围输入,并返回所有a的索引"""
indices = []
parts = a_range.split(',')
for part in parts:
if '-' in part:
start, end = map(int, part.split('-'))
indices.extend(range(start, end + 1))
else:
indices.append(int(part))
return indices


def modify_filename(filename, a_range):
"""根据a的范围修改文件名"""
new_name = list(filename)
a_indices = [i for i, char in enumerate(filename) if char in ['_', ' ']]
to_modify = parse_a_range(a_range)

for idx in to_modify:
if 0 < idx <= len(a_indices):
new_name[a_indices[idx - 1]] = '_'

for idx in a_indices:
if idx + 1 not in to_modify:
new_name[idx] = ' '

return ''.join(new_name)


def main():
while True:
try:
folder_path = input("请输入文件夹地址: ")
if not os.path.exists(folder_path) or not os.path.isdir(folder_path):
raise ValueError("指定的路径不存在或不是一个有效的文件夹!")

a_range = input("请输入a的范围 (例如: 1-5, 7 或 1,3,5,6-7): ")

for root, dirs, files in os.walk(folder_path):
for file in files:
if file.lower().endswith(('.png', '.jpg', '.jpeg')):
a_count = count_a(file)
print(f"'{file}' 中有 {a_count} 个a。")
new_name = modify_filename(file, a_range)
os.rename(os.path.join(root, file), os.path.join(root, new_name))
print(f"'{file}' 已经更名为 '{new_name}'。")

break

except ValueError as ve:
print(f"错误: {ve}")
except Exception as e:
print(f"发生异常: {e}")


if __name__ == "__main__":
main()