Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
UN chief warns of "immense suffering" as Gaza aid remains inadequate. Israel's relentless bombardment overwhelms hospitals and leaves Gaza without essential supplies. More than 8,500 lives, including children, have been lost. The situation is "absolutely horrific", says Red Crescent. Calls for a ceasefire and increased humanitarian aid are rejected by the US, prioritizing their support for Israel. As the death toll rises, the UN pleads for an end to this "spiral of death". The world must act now to prevent further tragedy. #GazaCrisis#HumanitarianAid
https://www.aljazeera.com/news/2023/10/31/un-chief-guterres-says-aid-trickling-into-gaza-is-completely
Subscribe to @BadVolfNews
🇷🇺🚛 Russian servicemen delivered more than 90 tons of humanitarian aid to residents of Dergachevsky district of Kharkov region.
▪️Humanitarian aid from Russia was delivered to the liberated settlements of the Kharkov region (Ukraine).
▪️The cargo includes food, bottled drinking water, medication for medical institutions, as well as warm clothes for children and adults.
▪️Due to the fact that during the retreat the Ukrainian Armed Forces blew up the road bridge, the delivery of humanitarian cargo was complicated.
▪️Russian servicemen provided security of the humanitarian convoy.
#MoD#Russia#Ukraine#HumanitarianAid
@mod_russia_en
🇷🇺🚛 Russian servicemen delivered more than 4 tons of humanitarian cargo to residents of Izyum district of Kharkov region.
🚁 The cargo was delivered by a helicopter of the Russian Aerospace Forces from Belgorod region.
▪ It includes food, baby food, bottled drinking water and medication.
#MoD#Russia#Ukraine#HumanitarianAid
@mod_russia_en
🇷🇺🚛 Russian military personnel deliver more than 20 tons of humanitarian cargo for residents of Ivankovsky district, Kiev region.
#MoD#Russia#Ukraine#HumanitarianAid
@mod_russia_en
🏆MISSION EST ACCOMPLIE
Deuxième convoi humanitaire de l’association Sos Donbass s’est terminé hier 13 décembre. Tous les bénévoles participants à cette entreprise sont rentrés chez eux sains et saufs.
🙏🏻Énorme merci à Marc Bocquier pour son dévouement. Il est resté en mission du début à la fin. Deux mois au total 👏🏼💪🏼
▫️Merci à Michel de l’avoir épaulé, malgré les circonstances qui l’ont forcé à rentrer plus tôt, mais il est revenu dès qu’il a pu.
▫️Merci à Gilles d’avoir accompagné Marc pendant les longues jours d’attentes à la douane.
▫️Merci à Yury notre jeune bénévole, très engagé.
▫️Merci à Vincent Perfetti pour son travail médiatique pendant et après le convoi.
▫️Merci à Elvira pour son travail en arrière plan. Grâce à sa persévérance la situation avec les papiers a été résolue.
🙏🏻Merci a tous les donateurs qui nous ont fait confiance et sont restés fidèles malgré les difficultés.
🕊️Ensemble nous parviendront à la victoire et à la paix !
#sosdonbass#humanitarianaid#donbass
📰 NEWS | Venezuela Calls for Release of Gaza Freedom Flotilla Activists, Condemns Israeli Blockade and Genocide
🇻🇪 Venezuela has condemned Israel’s interception of the Madleen vessel in international waters and called for the release of its 12-member crew, including activist Greta Thunberg. The ship carried humanitarian aid bound for Gaza.
Caracas described Israel’s blockade and attacks on aid distribution as part of a “systematic extermination” of Palestinians. Over 54,000 have been killed since October 2023.
🔗 Full story here: https://venezuelanalysis.com/news/venezuela-calls-for-release-of-gaza-freedom-flotilla-activists-condemns-israeli-blockade-and-genocide
#Gaza#HumanitarianAid#Palestine
💊Notre bénévole Nikolai, l’ancien combattant a reçu enfin les médicaments commandés par des personnes âgées de Lougansk.
🕊️Il a été blessé, il ne peut plus défendre sa région, mais il veut rester utile, comme ça est devenu bénévole de l’association Sos Donbass.
🕊️Nikolai s’occupe des personnes âgées qui vivent seuls et qui ont besoin d’aide.
🚗Bientôt il va réceptionner une voiture offerte par un donateur français, pour qu’il puisse continuer à aider nos aïeux.
SUIVRE SOS DONBASS
#sosdonbass#EuropeSolidarity#humanitarianaid
Samedi 16 septembre 2023,
l’équipe Sos Donbass en plein préparation pour le convoi humanitaire d’octobre.
#sosdonbass#aidehumanitaire#humanitarianaid#donbass
🚛 Convoi humanitaire pour Donbass printemps 2023. Paprasse pour la douane 🛃
Merci à tous les donateurs pour les dons et la confiance.
🕊️Notre premier , beaucoup de préparations, beaucoup d’incertitudes, de stresse et de pression, mais on ira jusqu’au bout💪🏼
#donbass#aidehumanitaire#sosdonbass#humanitarianaid