MJ数据处理:读取txt版

发布时间 2023-12-19 10:17:33作者: 不上火星不改名

读取文件夹内的txt名称,并根据该名称将其批量修改

import os
import re

UNWANTED_UNITS = ["undefined", "皮皮", "zly324"]
IMAGE_EXTENSIONS = [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff"]

# 检查文件是否为图片
def is_image_file(filename):
    _, ext = os.path.splitext(filename)
    return ext.lower() in IMAGE_EXTENSIONS

# 获取文件夹内第一个txt文件的名称(不包括扩展名)
def get_first_txt_title(path):
    try:
        for file in os.listdir(path):
            if file.endswith(".txt"):
                return os.path.splitext(file)[0]
    except FileNotFoundError:
        print(f"错误:指定的路径'{path}'不存在。")
    except Exception as e:
        print(f"发生错误:{e}")

    return None

# 生成唯一的新文件名
def generate_unique_filename(path, filename, ext):
    new_file_path = os.path.join(path, filename + ext)
    counter = 1
    while os.path.exists(new_file_path):
        new_file_path = os.path.join(path, f"{filename}({counter}){ext}")
        counter += 1
    return new_file_path

# 重命名图片文件
def rename_image_files(path, prefix):
    if not prefix:  # 如果没有找到txt文件或文件夹中没有txt文件
        print("未找到txt文件或txt文件为空,不进行重命名操作。")
        return

    try:
        files = [f for f in os.listdir(path) if is_image_file(f) and os.path.isfile(os.path.join(path, f))]
        counter = 1

        for file in files:
            filename, ext = os.path.splitext(file)
            # 乱码类
            if re.search(r'[a-f0-9]{32}', filename) or not '_' in filename:
                renamed = f"({counter})"
                counter += 1
            else:
                parts = re.split(r'[_]+', filename)
                parts.pop(0)  # 删除第一个单元

                # 删除特定的单元
                parts = [part for part in parts if part not in UNWANTED_UNITS]

                # 删除所有带数字的单元
                parts = [part for part in parts if not any(char.isdigit() for char in part)]

                # 删除特定规则的元素
                while parts and re.search(r'^[a-f0-9\-]{32,}$', parts[-1]):
                    parts.pop(-1)
                while parts and len(parts[-1]) <= 4:
                    parts.pop(-1)

                renamed = '_'.join(parts)

            # 添加前缀
            renamed = f"{prefix}_{renamed}"

            # 生成唯一的文件名
            new_file_path = generate_unique_filename(path, renamed, ext)
            os.rename(os.path.join(path, file), new_file_path)

        print("重命名完成。")
    except Exception as e:
        print(f"重命名过程中发生错误:{e}")

# 主函数
def main():
    path = input("请输入文件夹地址: ")
    prefix = get_first_txt_title(path)
    rename_image_files(path, prefix)

if __name__ == "__main__":
    main()