Created
November 26, 2014 21:53
-
-
Save adrienlachaize/47dd796917cd6b7cd1b1 to your computer and use it in GitHub Desktop.
Djang slugify a string to Twitter hashtag format
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 | |
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