From 867feb4904ca0548194b6cd4610cf4971c56aca8 Mon Sep 17 00:00:00 2001 From: Antonio de la Rosa Date: Tue, 19 Jan 2016 17:13:18 +0100 Subject: [PATCH] Added slugify function --- paramecio/citoplasma/slugify.py | 60 +++++++++++++++++++++++++++++++++ tests/slugifytest.py | 13 +++++++ 2 files changed, 73 insertions(+) create mode 100644 paramecio/citoplasma/slugify.py create mode 100644 tests/slugifytest.py diff --git a/paramecio/citoplasma/slugify.py b/paramecio/citoplasma/slugify.py new file mode 100644 index 0000000..fa57d6e --- /dev/null +++ b/paramecio/citoplasma/slugify.py @@ -0,0 +1,60 @@ +#!/usr/bin/python + +#A very simple version of strtr of php. + +def strtr(str_in, pat_str, rep_str): + + ret_str='' + + arr_dict={} + + if(len(pat_str)!=len(rep_str)): + raise NameError('Ups, pat_str len != rep_str len') + + #Create dictionary + + for (i, l) in enumerate(pat_str): + arr_dict[l]=rep_str[i] + + #Make a for to the str_in and substr. + + for le in str_in: + + if le in arr_dict: + + ret_str+=arr_dict[le] + + else: + ret_str+=le + + return (ret_str) + +def slugify(str_in, respect_upper=False, replace_space='-', replace_dot=False, replace_barr=False): + + str_out='' + + from_str='àáâãäåæçèéêëìíîïðòóôõöøùúûýþÿŕñÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÒÓÔÕÖØÙÚÛÝỲŸÞŔÑ¿?!¡()"|#*%,;+&$ºª<>`çÇ{}@~=^:´[]\'' + to_str= 'aaaaaaaceeeeiiiidoooooouuuybyrnAAAAAACEEEEIIIIDOOOOOOUUUYYYBRN----------------------------------' + + if replace_dot==True: + + from_str+='.' + from_to+='-' + + + if replace_barr==True: + + from_str+="/" + to_str+="-" + + str_out=str_in.strip() + + str_out=strtr(str_out, from_str, to_str) + + str_out=str_out.replace(" ", replace_space) + + if respect_upper==False: + pass + + return str_out + diff --git a/tests/slugifytest.py b/tests/slugifytest.py new file mode 100644 index 0000000..a177fd0 --- /dev/null +++ b/tests/slugifytest.py @@ -0,0 +1,13 @@ +from settings import config +from paramecio.citoplasma import slugify +import unittest + +class TestFieldMethods(unittest.TestCase): + + def test_slugify(self): + + phrase=slugify.slugify('this!()is a crap phrase o}çÇf oh yeah¡\'') + + self.assertEqual(phrase, 'this---is-a-crap-phrase-o---f-oh-yeah--') + + \ No newline at end of file