zvoase (owner)

Revisions

  • a705ef Sat Nov 22 10:36:11 -0800 2008
gist: 27914 Download_button fork
public
Public Clone URL: git://gist.github.com/27914.git
Embed All Files: show embed
slugify.py #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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