84 lines
2.5 KiB
Python
84 lines
2.5 KiB
Python
import os
|
|
import sys
|
|
import glob
|
|
|
|
try:
|
|
from opencc import OpenCC
|
|
except ImportError:
|
|
print("Error: 'opencc' package not found. Installing...")
|
|
import subprocess
|
|
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'opencc'])
|
|
from opencc import OpenCC
|
|
|
|
def convert_filename(filename, cc):
|
|
name, ext = os.path.splitext(filename)
|
|
simplified_name = cc.convert(name)
|
|
if simplified_name != name:
|
|
return simplified_name + ext
|
|
return None
|
|
|
|
def main():
|
|
if len(sys.argv) < 2:
|
|
print("Usage: python zhconv.py <path_to_file_or_folder>")
|
|
return
|
|
|
|
raw_input = sys.argv[1].strip(' "\'')
|
|
input_arg = os.path.abspath(raw_input)
|
|
print(f"Target: {input_arg}")
|
|
|
|
cc = OpenCC('t2s')
|
|
|
|
original_cwd = os.getcwd()
|
|
is_folder = False
|
|
|
|
if os.path.isfile(input_arg):
|
|
target_dir = os.path.dirname(input_arg)
|
|
target_files = [os.path.basename(input_arg)]
|
|
elif os.path.isdir(input_arg):
|
|
target_dir = input_arg
|
|
target_files = None
|
|
is_folder = True
|
|
else:
|
|
print(f"Error: Path '{input_arg}' does not exist.")
|
|
return
|
|
|
|
os.chdir(target_dir)
|
|
|
|
if target_files is None:
|
|
target_files = glob.glob('*')
|
|
|
|
converted_count = 0
|
|
for filename in target_files:
|
|
if not os.path.isfile(filename):
|
|
continue
|
|
new_filename = convert_filename(filename, cc)
|
|
if new_filename:
|
|
if os.path.exists(new_filename):
|
|
print(f"Skipped (already exists): {new_filename}")
|
|
else:
|
|
os.rename(filename, new_filename)
|
|
print(f"Converted: {filename} -> {new_filename}")
|
|
converted_count += 1
|
|
|
|
print(f"\nConverted {converted_count} file(s).")
|
|
|
|
os.chdir(original_cwd)
|
|
|
|
if is_folder:
|
|
folder_name = os.path.basename(target_dir)
|
|
new_folder_name = convert_filename(folder_name, cc)
|
|
if new_folder_name:
|
|
parent_dir = os.path.dirname(target_dir)
|
|
new_target_dir = os.path.join(parent_dir, new_folder_name)
|
|
if os.path.exists(new_target_dir):
|
|
print(f"Skipped folder (already exists): {new_folder_name}")
|
|
else:
|
|
try:
|
|
os.rename(target_dir, new_target_dir)
|
|
print(f"Converted folder: {folder_name} -> {new_folder_name}")
|
|
except Exception as e:
|
|
print(f"Warning: Could not rename folder '{folder_name}'. Ensure it is not in use. Error: {e}")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|