import os import re import unicodedata # 🔧 Thư mục chứa các file cần đổi tên DATA_DIR = "data/data_raw10k" LOG_FILE = "renamed_log.txt" def normalize_filename(name: str) -> str: """ Chuẩn hóa tên file: - Bỏ dấu tiếng Việt - Chuyển thành chữ thường - Thay khoảng trắng, ký tự đặc biệt thành '_' - Giữ lại phần mở rộng gốc (.txt) """ base, ext = os.path.splitext(name) # Bỏ dấu tiếng Việt base = unicodedata.normalize('NFKD', base).encode('ASCII', 'ignore').decode('utf-8') # Chuyển về chữ thường base = base.lower() # Thay mọi ký tự không phải chữ/số bằng "_" base = re.sub(r'[^a-z0-9]+', '_', base) # Bỏ ký tự "_" dư ở đầu/cuối base = base.strip("_") return f"{base}{ext}" def safe_rename(old_path: str, new_path: str) -> str: """ Nếu file trùng tên, thêm hậu tố _1, _2, ... """ base, ext = os.path.splitext(new_path) counter = 1 while os.path.exists(new_path): new_path = f"{base}_{counter}{ext}" counter += 1 os.rename(old_path, new_path) return new_path def rename_all_files(data_dir: str): renamed = [] for filename in os.listdir(data_dir): old_path = os.path.join(data_dir, filename) if not filename.lower().endswith(".txt"): continue new_name = normalize_filename(filename) new_path = os.path.join(data_dir, new_name) if old_path != new_path: new_path = safe_rename(old_path, new_path) print(f"✅ {filename} → {os.path.basename(new_path)}") renamed.append((filename, os.path.basename(new_path))) # Ghi log lại if renamed: with open(LOG_FILE, "w", encoding="utf-8") as f: for old, new in renamed: f.write(f"{old} → {new}\n") print(f"\n📝 Log đã lưu vào: {LOG_FILE}") else: print("Không có file nào được đổi tên.") if __name__ == "__main__": rename_all_files(DATA_DIR)