Skip to content

Instantly share code, notes, and snippets.

@fuji44
Last active June 15, 2021 21:38
Show Gist options
  • Save fuji44/6d21c1655b3d7e1f7b7d32ad3829a55c to your computer and use it in GitHub Desktop.
Save fuji44/6d21c1655b3d7e1f7b7d32ad3829a55c to your computer and use it in GitHub Desktop.
Replacing Invalid Characters as File Paths in Windows
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?
_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