Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🍂 “Our Lord has written the promise of resurrection, not in books alone but in every leaf of springtime.”
– Martin Luther
🌻look at the trees with fallen leaves during autumn, they keep on standing and stand strong despite many of their leaves fall down; as if they know and trust that they will not stay in that condition forever - in fact, they'll shine more beautifully soon when the spring comes. so dear, whenever you are in crestfallen, trust that that too shall pass.. be sad, but don't lose hope that tomorrow can be better☺️
#life#thoughts#sadness#happiness#motivation
@quietworld🍃
🍂 something you dislike happened? you couldn't get something you wish for? you have been disappointed and someone hurt you? you lost someone? you failed at something you hope you're good at?
and you feel sad about it?
then be so. feel sad. be sad. cry if you must. cry your heart out. let it out. it heals to cry. it heals to allow yourself to feel things; be human. because yes it is difficult to go through those things.
& that doesn't mean that you are weak. to feel those feelings are not a sign of weakness at all ; just that we are human, we are born with the ability to feel those emotions.
your strength is not determined by your ability to suppress emotions, but by your ability to overcome it; by not letting it controls yourself longer than it should be.
there's light at the end of the tunnel if you keep going.
#thoughts#notetoself#selfreminder#strength#positivity#sadness#motivation
@quietworld🍃
Collachrymate means to cry with someone or cry a lot until tears fall. It is an old English word from the 1500s and 1600s.
This word is not used anymore today.
Unless ofcours we revive it.😉
@googlefactss
#Words#OldEnglish#Cry#Sadness#Tears😢💧
L'amore ed i sentimenti in generale stanno vivendo una brutta epoca, sostituiti il più delle volte da pulsioni eremitiche.
#vaporonda#vaporwave#vapourwave#vaporart#seapunk#webpunk#glitch#glitchart#glitchartistscollective#chillwave#aesthetic#vaporwaveaesthetic#vaporwaveaesthetics#malinconia#melancholy#tristezza#sadness#sadboy#lofi#illusione#illusion#solitudine#loneliness#luciajavorcekova
La guerra é portatrice di ingiustizie ed inganni, di questi ultimi uno dei più grandi é quello di pretendere di costruire un mondo migliore.
#vaporonda#vaporwave#vapourwave#vaporart#seapunk#webpunk#glitch#glitchart#glitchartistscollective#chillwave#aesthetic#vaporwaveaesthetic#vaporwaveaesthetics#malinconia#melancholy#tristezza#sadness#sadboy#lofi#guerra#war#violenza#violence#illusione#illusion
Non é entusiasmante prendere consapevolezza di essere quasi coetaneo di Homer Simpson.
#vaporonda#vaporwave#vapourwave#vaporart#seapunk#webpunk#glitch#glitchart#glitchartistscollective#chillwave#aesthetic#vaporwaveaesthetic#vaporwaveaesthetics#malinconia#melancholy#tristezza#sadness#sadboy#lofi#simpson#simpsonwave#homer#homersimpson
Secondo me a livello culturale siamo immersi in una sorta di nuovo barocco, nell'accezione più deteriore del termine.
#vaporonda#vaporwave#vapourwave#vaporart#seapunk#webpunk#glitch#glitchart#glitchartistscollective#chillwave#aesthetic#vaporwaveaesthetic#vaporwaveaesthetics#malinconia#melancholy#tristezza#sadness#sadboy#lofi#apparenza#appearance#illusione#illusion#spettacolo#show
Mi sono stancato di influencer e tiktoker vari, buoni solo a pietrificare l'attenzione verso cose futili.
#vaporonda#vaporwave#vapourwave#vaporart#seapunk#webpunk#glitch#glitchart#glitchartistscollective#chillwave#aesthetic#vaporwaveaesthetic#vaporwaveaesthetics#malinconia#melancholy#tristezza#sadness#sadboy#lofi#apparenza#appearance#appearance#illusione#illusion#incubo#nightmare
Parole inconsistenti e pii desideri.
#vaporonda#vaporwave#vapourwave#vaporart#seapunk#webpunk#glitch#glitchart#glitchartistscollective#chillwave#aesthetic#vaporwaveaesthetic#vaporwaveaesthetics#malinconia#melancholy#tristezza#sadness#sadboy#lofi#illusione#illusion#utopia#razzismo#racism#cgil
Trovare le parole giuste con tutti e saper cogliere le sfumature di tutte quelle che ricevo, l'ho sempre trovato uno sforzo estremo.
#vaporonda#vaporwave#vapourwave#vaporart#seapunk#webpunk#glitch#glitchart#glitchartistscollective#chillwave#aesthetic#vaporwaveaesthetic#vaporwaveaesthetics#malinconia#melancholy#tristezza#sadness#sadboy#lofi#disagio#unease#comunicazione#communication#linguaggio#language
L'attaccamento agli oggetti é uno degli ostacoli maggiori per la nostra felicità, come se infondessimo in essi parte della nostra anima.
#vaporonda#vaporwave#vapourwave#vaporart#seapunk#webpunk#glitch#glitchart#glitchartistscollective#chillwave#aesthetic#vaporwaveaesthetic#vaporwaveaesthetics#malinconia#melancholy#tristezza#sadness#sadboy#lofi#disagio#nostalgia#illusione#illusion#windows95#windows98#windowsxp