(Lora训练)(承接midjourney数据修改)(建对应名称txt与删txt内部后缀,括号,数字与转换下划线)Lora数据处理新版

发布时间 2023-11-06 21:54:13作者: 不上火星不改名
import os
import re

def create_txt_from_image():
# 请求用户输入文件夹地址
root_folder = input("请输入图片所在文件夹的完整路径:")

# 判断路径是否存在
if not os.path.exists(root_folder):
print("路径不存在,请检查输入的地址。")
return

# 用于存储创建的txt文件路径的列表
created_txt_files = []

# 使用os.walk遍历文件夹及其所有子文件夹
for folder_path, dirs, files in os.walk(root_folder):
for file in files:
# 检查文件是否为图片(这里我们检查几种常见的图片格式)
if file.endswith(('.jpg', '.png', '.jpeg')):
# 获取不带扩展名的文件名
base_name = os.path.splitext(file)[0]

# 创建同名的txt文件路径
txt_path = os.path.join(folder_path, base_name + '.txt')
created_txt_files.append(txt_path)

# 将图片文件名(不包括后缀)写入到txt文件中
with open(txt_path, 'w', encoding='utf-8') as txt_file:
txt_file.write(base_name)

print("所有图片对应的txt文件已创建完毕。")

# 编译正则表达式以匹配括号及括号内的数字
bracket_pattern = re.compile(r'\(\d+\)')
underscore_pattern = "_" # 不需要正则表达式匹配单个字符

# 遍历所有txt文件,进行内容修改
for txt_file_path in created_txt_files:
with open(txt_file_path, 'r', encoding='utf-8') as file:
content = file.read()

# 删除内容中的括号及括号内的数字
content = bracket_pattern.sub('', content)
# 把下划线替换成英文逗号
content = content.replace(underscore_pattern, ",")

with open(txt_file_path, 'w', encoding='utf-8') as file:
file.write(content)

print("所有txt文件内容中的括号及括号内的数字已删除,并且所有下划线已转换为英文逗号。")

# 运行函数
create_txt_from_image()