Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🌎 In ancient China, giant panda pelts were considered symbols of peace and friendship. Emperors gifted them to rival kingdoms as precious gestures, showing diplomacy in action through nature’s rarest bear. ✨
#history⚡#animals⚡#diplomacy
👉subscribe Interesting Planet
🚨🇺🇸TRUMP TELLS IRAN "CALL US" AS PUTIN HOSTS TEHRAN'S TOP DIPLOMAT
🔹 Iranian Foreign Minister Abbas Araghchi lands in St. Petersburg today for emergency talks with Putin 🇷🇺
🔹 Trump abruptly canceled US-Iran face-to-face meeting scheduled in Pakistan, blaming Tehran's "excessive demands" 📞❌
🔹 Nine-week conflict continues with mutual blockades choking energy markets — oil prices surge nationwide 💰⛽
🔹 Strait of Hormuz remains partially closed as Iran seeks Russian backing after US diplomacy collapsed 🚢🔒
"The ball is in their court — call us when you're ready to be serious," Trump signals 📱
This is getting messy fast 😬🔥
#USNews#Iran#diplomacy
@america
Faces of #Uzbekistan#Diplomacy
Ambassadors, permanent representatives and general consuls of Uzbekistan abroad with the First Deputy Chair of the Senate of the Parliament Sodyq Safaev and the Deputy Minister of Foreign Affairs Sherzod Asadov, after the seminar training organised by the Senate.
P.S. Could you find only two women?
@Diplomatika
🚨🇺🇸U.S. INTEL: IRAN REJECTS PEACE TALKS
🔹 Multiple intelligence agencies assess Tehran unwilling to negotiate seriously 🕵️♂️
🔹 Iran believes it's winning, doesn't trust Trump after previous attacks mid-negotiations 💪
🔹 Trump claims military will wrap up Iran campaign within 2-3 weeks ⏰
🔹 President threatens to bomb ALL Iranian power plants if no deal - potential war crime ⚡
🔹 Tehran foreign ministry denies asking for ceasefire despite Trump's progress claims 🗣️
Iran wants real peace talks, not temporary fixes according to Pakistani officials! This war is FAR from over 😤🔥
#USNews#Iran#Trump#diplomacy
@america
🌍 The Arctic Council brings together eight countries to manage Arctic resources and navigate disputes, making this region one of the world’s best examples of peaceful geopolitical cooperation. ✨
#geopolitics⚡#Arctic⚡#diplomacy⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
The Venezuelan government accepted Washington’s offer to restart dialogue only weeks ahead of presidential elections on July 28. President Maduro emphasizes any talks will have Venezuela's sovereignty as a starting point.
Full story: https://venezuelanalysis.com/news/venezuela-to-restart-direct-talks-with-us-maduro-announces/
#Venezuela#UnitedStates#Diplomacy
🚨🇨🇺🇺🇸CUBA CONFIRMS SECRET TALKS WITH TRUMP ADMINISTRATION
🔹 Cuban President Díaz-Canel publicly admits holding bilateral talks with US officials 🤝
🔹 Discussions aim for historic economic deal - biggest opening since 1961 revolution 💰
🔹 Cuba releases 51 prisoners as Vatican-brokered goodwill gesture ahead of negotiations 🕊️
🔹 Trump threatens "friendly takeover" if Cuba refuses to make deal with Washington 💪
🔹 Island faces fuel crisis with NO oil shipments for 3 months due to US blockade ⛽
🔹 Secretary Rubio reportedly in secret talks with Raul Castro's grandson Raulito 🤐
This could END 65 years of Cold War hostility - but at what price? 🔥🌎
#Cuba#diplomacy#Trump
@america
📰 NEWS | Venezuela Reclaims US Diplomatic Venues as Rodríguez Promotes ‘Faith Diplomacy’
Venezuela has officially retaken its diplomatic headquarters in Washington, DC, after the properties were under US State Department control since 2023. Officials re-hoisted the national flag and announced a rehabilitation process to restore full consular services for Venezuelan nationals.
The development follows renewed diplomatic ties between Caracas and Washington and a US sanctions waiver permitting operations of Venezuelan missions. Authorities say the facilities will address passport processing, legal documentation, and citizen assistance after years of restricted access.
Read the full report here 👉🏾https://venezuelanalysis.com/news/venezuela-reclaims-us-diplomatic-venues-as-rodriguez-promotes-faith-diplomacy/
#diplomacy#Religion#USVenezuelaRelations
politics
Somaliland and the Evolution of Diplomatic Engagement After 34 Years of Isolation. Read.
https://borkena.com/2026/01/01/somaliland-and-the-evolution-of-diplomatic-engagement-after-34-years-of-isolation/#SomalilandRecognition#Somaliland#Diplomacy