Created
November 22, 2008 18:36
-
-
Save zvoase/27914 to your computer and use it in GitHub Desktop.
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
import random | |
import re | |
import unicodedata | |
def slugify(string, randlen=10): | |
string_out = '' | |
for char in string: | |
if char.isspace(): | |
string_out += '-' | |
elif re.match('[A-Za-z0-9-_]', char): | |
string_out += char.lower() | |
else: | |
norm = unicodedata.normalize('NFKD', char)[0].encode('ascii', | |
'ignore') | |
if re.match('[A-Za-z0-9-_]', norm): | |
string_out += norm.lower() | |
string_out = remove_duplicates(string_out.strip('-_'), '-_') | |
if not re.match(r'[A-Za-z0-9-_]+', string_out): | |
return ''.join( | |
random.choice(string.ascii_letters + '-_') | |
for i in range(randlen)).strip('-_') | |
return string_out | |
def remove_duplicates(string, characters): | |
for char in characters: | |
string = re.sub('(%s)+' % re.escape(char), char, string) | |
return string |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment