Skip to content

Instantly share code, notes, and snippets.

@adrienlachaize
Created November 26, 2014 21:53
Show Gist options
  • Save adrienlachaize/47dd796917cd6b7cd1b1 to your computer and use it in GitHub Desktop.
Save adrienlachaize/47dd796917cd6b7cd1b1 to your computer and use it in GitHub Desktop.
Djang slugify a string to Twitter hashtag format
import re
import unicodedata
try:
from django.utils.encoding import smart_unicode as smart_text
except ImportError:
from django.utils.encoding import smart_text
SLUG_OK = '_'
def slug_twitter(s, ok=SLUG_OK, lower=True, spaces=False):
"""
Slugify a string to Twitter hashtag format
"""
rv = []
for c in unicodedata.normalize('NFKC', smart_text(s)):
cat = unicodedata.category(c)[0]
if cat in 'LN' or c in ok:
rv.append(c)
if cat == 'Z': # space
rv.append(' ')
new = ''.join(rv).strip()
if not spaces:
new = re.sub('[-\s]+', '_', new)
return new.lower() if lower else new
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment