Last active
February 17, 2018 11:52
-
-
Save ranelpadon/c21e1c96befff808abd9ef4ff8a2f773 to your computer and use it in GitHub Desktop.
Find the restricted symbols in the text and substitute with multiple replacement values.
This file contains hidden or 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
import re | |
# Restricted symbols taken from https://en.wikipedia.org/wiki/Filename | |
symbols = ('/', '\\', '?', '%', '*', ':', '|', '"', '<', '>',) | |
symbols_replacements = {symbol: '_' for symbol in symbols} | |
space_replacement = {' ': '-'} # Dash instead of underscore | |
replacements = {} | |
replacements.update(symbols_replacements) | |
replacements.update(space_replacement) | |
text = 'Hello World 01/01/1970 a/b\c?d%e*f:g|h<i>j"' | |
# Solution 1 | |
for pattern, repl in replacements.iteritems(): | |
text = re.sub(re.escape(pattern), repl, text) | |
# Solution 2 | |
# pattern = re.compile('|'.join(map(re.escape, replacements.keys()))) | |
# text = pattern.sub(lambda match: replacements[match.group(0)], text) | |
# Output: Hello-World-01_01_1970--a_b_c_d_e_f_g_h_i_j_ | |
print text |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment