Certainly! To modify the sanitize_filename function to replace characters based on your specified mapping, you can use a dictionary that explicitly maps each original character to its desired replacement. This approach ensures precise control over the sanitization process, especially for characters with accents or special forms.
Below is the updated sanitize_filename function that incorporates the specified character replacements:
import re
def sanitize_filename(name):
"""
Sanitize the folder name by replacing specific characters based on a mapping,
converting to lowercase, and replacing spaces and special characters with hyphens.
Args:
name (str): Original folder name.
Returns:
str: Sanitized folder name.
"""
# Define the character mapping based on the provided original and result lists
char_map = {
# 'a' mappings
'a': 'a', 'à': 'a', 'á': 'a', 'ả': 'a', 'ã': 'a', 'ạ': 'a',
'ă': 'a', 'ằ': 'a', 'ắ': 'a', 'ẳ': 'a', 'ẵ': 'a', 'ặ': 'a',
'â': 'a', 'ấ': 'a', 'ầ': 'a', 'ẩ': 'a', 'ẫ': 'a', 'ậ': 'a',
# 'b' to 'c'
'b': 'b', 'c': 'c',
# 'd' mappings
'd': 'd', 'đ': 'd',
# 'e' mappings
'e': 'e', 'é': 'e', 'è': 'e', 'ẻ': 'e', 'ẽ': 'e', 'ẹ': 'e',
'ê': 'e', 'ế': 'e', 'ề': 'e', 'ể': 'e', 'ễ': 'e', 'ệ': 'e',
# 'g' to 'h'
'g': 'g', 'h': 'h',
# 'i' mappings
'i': 'i', 'í': 'i', 'ì': 'i', 'ỉ': 'i', 'ĩ': 'i', 'ị': 'i',
# 'k' to 'm'
'k': 'k', 'l': 'l', 'm': 'm',
# 'n' mappings
'n': 'n',
# 'o' mappings
'o': 'o', 'ó': 'o', 'ò': 'o', 'ỏ': 'o', 'õ': 'o', 'ọ': 'o',
'ô': 'o', 'ố': 'o', 'ồ': 'o', 'ổ': 'o', 'ỗ': 'o', 'ộ': 'o',
'ơ': 'o', 'ớ': 'o', 'ờ': 'o', 'ở': 'o', 'ỡ': 'o', 'ợ': 'o',
# 'p' to 's'
'p': 'p', 'q': 'q', 'r': 'r', 's': 's',
# 't' mappings
't': 't',
# 'u' mappings
'u': 'u', 'ú': 'u', 'ù': 'u', 'ủ': 'u', 'ũ': 'u', 'ụ': 'u',
'ư': 'u', 'ứ': 'u', 'ừ': 'u', 'ử': 'u', 'ữ': 'u', 'ự': 'u',
# 'v' to 'x'
'v': 'v', 'x': 'x',
# 'y' mappings
'y': 'y', 'ý': 'y', 'ỳ': 'y', 'ỷ': 'y', 'ỹ': 'y', 'ỵ': 'y',
# 'z', 'w', 'f', 'j'
'z': 'z', 'w': 'w', 'f': 'f', 'j': 'j',
# Space to hyphen
' ': '-'
}
# Convert the name to lowercase to ensure uniformity
name = name.lower()
# Replace each character based on the mapping; if not found, use a hyphen
sanitized = ''.join([char_map.get(char, '-') for char in name])
# Replace multiple consecutive hyphens with a single hyphen
sanitized = re.sub(r'-+', '-', sanitized)
# Remove leading and trailing hyphens
sanitized = sanitized.strip('-')
return sanitized
Explanation of the Modifications
-
Character Mapping (char_map):
- A dictionary named
char_map is created to map each original character to its desired replacement as specified.
- All accented versions of a character (e.g.,
'à', 'á', 'ả', etc.) are mapped to their base character (e.g., 'a').
-
Lowercasing the Input:
- The input
name is converted to lowercase to ensure consistency, as the mapping is defined in lowercase.
-
Character Replacement:
- The function iterates over each character in the input
name.
- For each character, it retrieves the corresponding replacement from
char_map.
- If a character isn't found in
char_map, it defaults to replacing it with a hyphen ('-').
-
Handling Multiple Hyphens:
- After the initial replacement, there might be multiple consecutive hyphens, especially if there were consecutive characters that were replaced with hyphens.
- The
re.sub(r'-+', '-', sanitized) line replaces any occurrence of one or more hyphens with a single hyphen.
-
Trimming Hyphens:
- Leading and trailing hyphens are removed using
strip('-') to ensure the sanitized filename doesn't start or end with a hyphen.
Examples
Let's see how this function works with some examples:
# Example 1
original_name = "Đỗ Văn A"
sanitized = sanitize_filename(original_name)
print(sanitized) # Output: "do-van-a"
# Example 2
original_name = "Café Đẹp! @ 2024"
sanitized = sanitize_filename(original_name)
print(sanitized) # Output: "cafe-dep-2024"
# Example 3
original_name = "Kỹ Thuật Phần Mềm #1"
sanitized = sanitize_filename(original_name)
print(sanitized) # Output: "ky-thuat-phan-mem-1"
Notes
-
Flexibility: This approach provides precise control over how each character is handled, which is especially useful for languages with rich diacritic systems like Vietnamese.
-
Extensibility: If you need to handle more characters or different mappings in the future, you can easily update the char_map dictionary.
-
Performance Consideration: For very long strings, you might want to optimize the replacement process, but for typical folder names, this implementation should perform efficiently.
Alternative Approach Using Unicode Normalization
If you're dealing primarily with standard accented characters and don't need specific mappings beyond removing diacritics, you can utilize Unicode normalization as in your original function. However, since you have specific requirements (like replacing 'đ' with 'd'), the explicit mapping approach ensures accuracy.
import re
import unicodedata
def sanitize_filename(name):
"""
Sanitize the folder name by replacing 'đ' with 'd', removing accents,
converting to lowercase, and replacing spaces and special characters with hyphens.
Args:
name (str): Original folder name.
Returns:
str: Sanitized folder name.
"""
# Step 1: Replace 'đ' and 'Đ' with 'd' and 'D' respectively
name = name.replace('đ', 'd').replace('Đ', 'D')
# Step 2: Normalize the string to NFD to separate accents from characters
nfkd_form = unicodedata.normalize('NFD', name)
# Step 3: Encode to ASCII bytes, ignoring characters that can't be encoded
only_ascii = nfkd_form.encode('ASCII', 'ignore').decode('utf-8')
# Step 4: Replace any non-alphanumeric characters with hyphens
sanitized = re.sub(r'[^a-z0-9]+', '-', only_ascii.lower()).strip('-')
return sanitized
This alternative is simpler but may not handle all your specific cases precisely, especially if there are unique characters like 'ư' that need to be mapped differently.
Feel free to choose the approach that best fits your requirements!