Last active
June 15, 2021 21:38
-
-
Save fuji44/6d21c1655b3d7e1f7b7d32ad3829a55c to your computer and use it in GitHub Desktop.
Replacing Invalid Characters as File Paths in Windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from .util import replace_invalid_char | |
extension_map = { | |
"&": "&", | |
"(": "(", | |
")": ")", | |
"[": "[", | |
"]": "]", | |
"{": "{", | |
"}": "}", | |
"^": "^", | |
"=": "=", | |
";": ";", | |
"!": "!", | |
"'": "’", | |
"+": "+", | |
",": ",", | |
"`": "‘", | |
"~": "~", | |
"#": "#", | |
"%": "%", | |
".": ".", | |
"$": "$", | |
# " ": " ", | |
} | |
sample1 = "[TAG] sample! & sample?" | |
print(replace_invalid_char(sample1)) | |
# [TAG] sample! & sample? | |
print(replace_invalid_char(sample1, extension_map)) | |
# [TAG] sample! & sample? |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_default_invalid_char_map = { | |
"\\": "¥", | |
"/": "/", | |
":": ":", | |
"*": "*", | |
"?": "?", | |
'"': "”", | |
">": ">", | |
"<": "<", | |
"|": "|", | |
} | |
def replace_invalid_char(text: str, ext: dict[str, str] = None): | |
if ext: | |
char_map = dict(**_default_invalid_char_map, **ext) | |
else: | |
char_map = dict(**_default_invalid_char_map) | |
trantable = str.maketrans(char_map) | |
return text.translate(trantable) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment