from googletrans import Translator
import os
def sanitize_filename(filename):
# Remove or replace disallowed characters in the filename
sanitized_name = filename.replace('\\', '_').replace('/', '_').replace('?', '').replace('*', '')
return sanitized_name
def translate_file_name(file_path, target_language='en'):
# Extract the directory, file name, and extension
directory, filename = os.path.split(file_path)
file_name, file_extension = os.path.splitext(filename)
# Translate the file name
translator = Translator()
translated_name = translator.translate(file_name, dest=target_language).text
# Sanitize the translated name
sanitized_name = sanitize_filename(translated_name)
# Construct the new file path with the sanitized translated name and the original extension
translated_file_path = os.path.join(directory, sanitized_name + file_extension)
# If the translated file already exists, add a suffix to make it unique
counter = 1
while os.path.exists(translated_file_path):
translated_file_path = os.path.join(directory, f'{sanitized_name}_{counter}' + file_extension)
counter += 1
# Print the original and translated file paths
print(f'Original File Path: {file_path}')
print(f'Translated File Path: {translated_file_path}')
# Rename the file
os.rename(file_path, translated_file_path)
# Specify the directory containing your txt files
directory_path = r'D:\目录'
# List all files in the directory
for filename in os.listdir(directory_path):
if filename.endswith(".mp4"):
file_path = os.path.join(directory_path, filename)
translate_file_name(file_path)