Skip to content

Python - Slugger

Description

Here is a small python function to convert an article title to a slugger.

It's a alternative to python library like:

  • slugger
  • django-slugger

 

Arguments

See function arguments :

  • Text to convert
  • Encoding (Default: utf-8)

 

Modules

Les modules utilisés sont :

  • unicodedata, which removes punctuation
  • re, which allows you to use regular expressions and replace characters with other (sub)

 

Code

import unicodedata
import re

def sluger_fmt(text, encoding='utf-8'):
    sluger = unicode(text, encoding).lower()
    sluger = unicodedata.normalize('NFD', sluger).encode('ascii', 'ignore')
    sluger = re.sub(r'[\(\)\[\]\']', '', sluger)
    sluger = re.sub(r'[ \/]', '-', sluger)

    return sluger

Examples

print sluger_fmt('Crème Brulée à la Vanille façon LoKo (Ying/Yang Style)')
# creme-brulee-a-la-vanille-facon-loko-ying-yang-style

print sluger_fmt('Fonction Python permettant la Conversion d\'un Titre en Slugger (Django)')
# fonction-python-permettant-la-conversion-dun-titre-en-slugger-django
Back to top