Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🌎 Trapped in an Andes avalanche in 1972, survivors of a plane crash endured 72 days in freezing mountains, rationing food and melting snow for water—proving human resilience in the harshest conditions. ✨
#survival⚡#history⚡#resilience
👉subscribe Interesting Planet
🌎 The Resurrection Fern can survive months or years without rain by curling up and looking dead. With just a splash of water, it springs back to vibrant green life, showcasing an extraordinary natural survival trick for drought-prone environments. ✨
#plants⚡#adaptation⚡#resilience
👉subscribe Interesting Planet
🌍 Some coral reefs in the Red Sea host unique fish and coral species that can tolerate extreme heat and high salt levels, making them among the most resilient reef ecosystems on Earth. ✨
#coral⚡#marine⚡#resilience⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
Ad Al-Wafa, a Gaza, questa settimana si è celebrata la cerimonia di fine anno scolastico per migliaia di bambini.
Un evento che in condizioni normali sarebbe stato occasione di festa ma che si è trasformato in un momento intriso di dolore. I volti dei piccoli brillavano d’orgoglio mentre ricevevano i diplomi ma dietro ai sorrisi si nascondeva un vuoto profondo: nessun genitore ad applaudirli, nessuno a scattare foto o a sussurrare parole di incoraggiamento.
Un rapporto dell’ONU rivela che oltre il 90 % delle scuole e università sono state danneggiate o distrutte, privando dell’istruzione più di 800.000 bambini e ragazzi e interrompendo la vita accademica di circa 90.000 universitari. Oggi tutti questi ragazzi studiano in tende di fortuna gestire da Unicef, ONU E UNRWA continuamente bersagliate dall’artiglieria di Israele.
#gazagenocide#gazastudents#resilience
🌎 Trapped under debris for 17 days after a 2015 Nepal earthquake, Pemba Tamang survived by drinking muddy water dripping from rubble and eating small snacks. He emerged with only minor injuries after nearly 2½ weeks underground, making it one of the longest earthquake survival cases recorded. ✨
#survival⚡#earthquake⚡#resilience
👉subscribe Interesting Planet
👉more Channels
🌎 The tardigrade’s cousin, the rotifer, can survive drying out for decades by entering a state called cryptobiosis. When water returns, it wakes up as if nothing happened, showing remarkable resilience in the micro-world. ✨
#rotifer⚡#cryptobiosis⚡#resilience
👉subscribe Interesting Planet
As the 60-day ceasefire deadline ended, the people of southern #Lebanon returned to their homes despite Israeli violence. 15 martyrs and 83 injured in the ongoing struggle for their land.
#DayOfReturn#CeasefireDeadline#Resilience#Israel#SouthernLebanon#Occupation
After over a year of displacement, the people of southern #Lebanon return—not to homes, but to the land scarred by Israeli aggression. Their spirit is unbroken.
#Resilience#SouthernLebanon#ReclaimingHome#Rebuilding#Israel#LebaneseArmy
🚀 South Korea's Central Bank Governor: Export Performance Exceeds Expectations
South Korea's central bank governor, Lee Chang-yong, has stated that the country's export performance has surpassed expectations. According to Jin10, Lee highlighted the positive export figures during a recent address, noting that the results are better than initially anticipated. This development comes amid ongoing global economic challenges, where South Korea's export sector has shown resilience and adaptability. The improved export performance is seen as a crucial factor in supporting the nation's economic stability and growth. Lee's remarks underscore the importance of exports in South Korea's economic strategy, as the country continues to navigate complex international trade dynamics.
#SouthKorea#CentralBank#ExportPerformance#EconomicGrowth#GlobalEconomy#Resilience#TradeDynamics#LeeChangYong#EconomicStability
When kids have big emotions, we tend to think they are being overly sensitive, that they need more resilience. Most of the time it is because there is a lot happening for the child that we can't see and don't know, that is pushing them beyond their means of coping. Instead we can change the response from they are overreacting, to seeing a child who has a lot happen for them, they are doing the best they can. They need our help not judgement.
#parenting#positiveparenting#gentleparenting#resilience#respectfulparenting#psychologist#play#playtherapy#childdevelopment#childtherapy#parentingtips#teachers#asd#family#life#adhd#mumlife#momlife#dads#consciousparenting
https://www.instagram.com/p/Ctd93W8vEM9/