Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для URL, имени файла, имени объекта в каком-то софте и тд. Требования совместимости простые: в тексте должны быть только допустимые символы. Обычно это a-z, 0-9 и "_" или "-". То есть, только прописные буквы латинского алфавита и цифры (как пример).
Допустим, нам нужно название статьи в блоге преобразовать в slug для добавления его в URL этой статьи. Как это лучше всего сделать?
В Django по умолчанию есть готовая функция slugify для таких случаев.
Но я её никогда не использую. Почему? Потому что её недостаточно!
Приведём пример
>>> from django.utils.text import slugify
>>> slugify('This is a Title')
'this-is-a-title'
Пока всё отлично
>>> slugify('This is a "Title!"')
'this-is-a-title'
Спец символы удалились, всё хорошо.
>>> slugify('Это заголовок статьи')
''
Вот и приехали 😢. Если текст не английский то буквы просто игнорируются. Можно это поправить
>>> slugify('Это заголовок статьи', allow_unicode=True)
'это-заголовок-статьи'
Но тогда мы не вписываемся в условие. У нас появилась кириллица в тексте.
Так как я часто пишу сайты для русскоязычных пользователей эта проблема весьма актуальна. Я не использую стандартную функцию и всегда пишу свою.
Оригинал я не беру в расчёт и пишу полностью свою функцию. И так, по порядку:
🔸1. Исходный текст:
>>> text = 'Мой заголовок №10 😁!'
Взял специально посложней со специальными символами.
🔸2. Транслит
Необходимо сделать транслит всех символов в латиницу. Здесь очень выручает библиотека unidecode. Помимо простого транслита кириллицы в латиницу она умеет преобразовывать спец символы и иероглифы в текстовые аналоги.
from unidecode import unidecode
>>> unidecode("Ñ Σ ® µ ¶ ¼ 月 山")
'N S (r) u P 1/4 Yue Shan'
Очень крутая библиотека, советую👍
В нашем случае получаем такое преобразование:
>>> text = unidecode(text)
>>> print(text)
'Moi zagolovok No. 10 !'
Отличный транслит. Смайл просто удалился, хотя я ждал что-то вроде :). Ну и ладно, всë равно невалидные символы.
А еще наш код уже поддерживает любой язык, будь то хинди или корейский.
🔸4. Фильтр символов
Unidecode не занимается фильтрацией по недопустимым символам. Это мы делаем в следующем шаге через regex. Просто заменим все символы на "_" если они вне указанного диапазона.
>>> text = re.sub(r'[^a-zA-Z0-9]+', '_', text)
>>> print(text)
'Moi_zagolovok_No_10_'
Символ "+" в паттерне выручает когда несколько недопустимых символов идут рядом. Все они заменяются на один символ "_".
🔸5. Slugify
Осталось удалить лишние символы по краям и сделать нижний регистр
>>> text = text.strip('_').lower()
>>> print(text)
'moi_zagolovok_no_10'
Получаем отличный slug! 😎
🌎 Полный код в виде функции.
______________
PS. Проверку что в строке остался хоть один допустимый символ я бы вынес в отдельную функцию.
#libs#tricks#django
Episode 1: She’s in his hoodie, sitting cross-legged on the kitchen counter while he flips pancakes. Music plays low, something nostalgic. She sways, miming the lyrics with lazy exaggeration. He grins—half amusement, half adoration. There’s no rush. No plan. Just the rhythm of a morning made soft by love.
❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️
We keep finding heaven in the smallest things.
❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️
#lovelived#iloveyou
Episode 16
The villa deck hums with sunlight, the ocean below impossibly clear — liquid turquoise stretching forever. He hits the water first, surfacing with a splash and boyish triumph, pushing wet hair from his eyes.
“Come on!” he calls, treading water, arms open like the sea is his idea.
She sits at the top of the slide, toes curled over the edge, laughter already bubbling in her chest. The world feels weightless up here — sky, water, horizon all blending into one endless promise. She looks at him, glowing down there, and shakes her head like she can’t believe this is real.
He cheers louder. She leans back, breath caught between thrill and trust — and lets go.
If you jump, I jump. Every lifetime.
📖 Read on Wattpad
🎧 Love, Lived I Album
#lovelived#lovelived2#theeverydaymagic
❤️ YouTube | Instagram ❤️
Episode 15
Thursday afternoons belong to sugar and sunlight. They don’t debate flavors anymore—she reaches for hers, he for his, like muscle memory. The shop owner already knows their order. They walk slowly, cones melting faster than planned, shoulders brushing, trading bites without asking. Workdays soften. The week exhales. Love tastes like something cold and sweet, shared halfway down the block.
Traditions are just love that learned the schedule. 🍦✨
📖 Read on Wattpad
🎧 Love, Lived I Album
#lovelived#lovelived2#theeverydaymagic
❤️ YouTube | Instagram ❤️
Episode 14
The kitchen smells like garlic and sun-warmed tomatoes. She stirs the pasta with one hand, dancing slightly to a morning playlist. He sits at the table, laptop open but eyes drifting. The new vase sits between them, holding sunflowers like a little sun of its own. He types. She tastes. The space hums—spoon clinks, keys click, love simmering in the background.
A bouquet, a bowl of pasta, and you across the table. Perfect.
📖 Read on Wattpad
🎧 Love, Lived I Album
#lovelived#lovelived2#theeverydaymagic
❤️ YouTube | Instagram ❤️
Episode 13
She wakes to the smell of something warm, sweet, familiar. The dining room glows—sunlight spilling in through the floor-to-ceiling glass wall, kissing every detail he carefully placed: fresh fruit gleaming in bowls, milk in a glass pitcher, her favorite breakfast dish plated like art, dessert waiting with a ribbon on the side, the sunflower-filled vase watching quietly.
He stands there—apron still crooked, cheeks a little pink.
“I want you to break your fast with your favorite dish made by me. I poured all my love into it. Happy birthday, my love.”
She doesn’t sit right away.
She hugs him first. Slow. Long. Like she tasted the love before the food.
This morning, love tasted homemade.
📖 Read on Wattpad
#lovelived#lovelived2#theeverydaymagic
Episode 12
The beach is empty—except for them. Lanterns flicker in glass jars, fairy lights drape over driftwood like fallen stars. A small table for two sits on a sand-carved rug, scattered with rose petals and sea breeze. She stops walking, hand over her mouth, dress brushing the shore. He watches her—not the waves, not the lights—her. She turns, eyes glossy, and breathes, “This feels unreal.” He smiles. “Then we’re right on time.”
The world paused—so we could celebrate you.
📖 Read on Wattpad
#lovelived#lovelived2#theeverydaymagic