Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
Sheep can feel emotions like fear, anger, boredom, and happiness. They evaluate their surroundings using checks like suddenness, familiarity, predictability, and control, similar to humans. Sudden events can cause fear, while predictable environments may lead to boredom.
🐑⚽️
@googlefactss
#AnimalWelfare#Sheep#Emotions#AnimalCare#Nature
🇳🇴 NORWAY PHASES OUT UNNATURALLY FAST-GROWING “FRANKEN-CHICKENS”
Norway has announced a gradual phase-out of so-called “franken-chickens” by 2027.
Norway, where about 70 million chickens are raised annually for food production, has become the first country to commit to raising 100% of its poultry under conditions that ensure high animal welfare standards. Animal rights advocates have welcomed the decision, calling it a “historic moment.”
“Franken-chickens,” often referred to in Norway as “turbo-chickens,” are fast-growing birds bred through selective breeding to reach maximum weight in the shortest possible time. Due to rapid growth and extreme size, these chickens suffer from numerous health problems, and most animal welfare organizations strongly condemn this practice.
According to Humane World for Animals, franken-chickens reach their “slaughter weight” in just six weeks, leading to severe strain on their bones, muscles, and ligaments. Their bodies often begin to break down as they grow, and many birds lose the ability to move. Humane League UK describes their lives as “extremely short and painful.”
The animal protection coalition Anima International has been campaigning for five years to eliminate fast-growing chicken breeds in Norway. Several animal welfare groups are also calling for similar measures in the United Kingdom.
Experts emphasize that this decision marks a significant step forward in improving animal welfare.
#AnimalRights#Norway#AnimalWelfare#PoultryFarming#ProtectAnimals
☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot
Instagram | Facebook | Twitter | Sayt | Youtube
#ForBritain policy: Fully investigate #BadgerCulling with the aim of bringing it to an end.
#AnimalWelfare#BadgerCull#BanBadgerCulling
Full manifesto here: https://www.forbritain.uk/manifesto/
🐾 WEBINAR ALERT: Rabies Elimination and Animal Welfare 🐾
Join us for a focused, hard-hitting session featuring leading voices in veterinary medicine, public health, and youth advocacy. Our expert panel will break down the most pressing issues, from emergency shelter response to global rabies elimination strategies.
📅Date: Feb 19
⏰Time: 2:30 L.T
📍Platform: t.me/aau_ohc
🎤MEET THE PANELISTS:
🔹 Dr. Mesfin Semu Wodajo
Graduate of Moscow Veterinary Academy (1994) and Utrecht University (2000). Former Associate Researcher at Tetracore, LLC. 14 years as Chief of Staff at Banfield Pet Hospital. Currently Medical Director & Owner at Upper Marlboro Veterinary Hospital.
🔹 Dr. Alazar Ayele
Veterinarian specializing in mobile pet care. Co-founder of Beyond Student for Change initiative. Operates a mobile veterinary clinic to expand access to professional animal healthcare and leads community-based stray dog mass rabies vaccination campaigns.
🔹 Dr. Biruk Eshetu
University of Gondar graduate (2015 E.C.). Former founder & president of One Health Innovation Club and VP of Clinical Medicine Club at UoG. Currently Manager of the Animal Welfare and Protection Trauma Shelter, Addis Ababa, where he works extensively with pets and shelter animals.
🔹 Yared Ermiyas
DVM Candidate, Co-founder of AAU One Health Club, and Animal Welfare Advocate.
🎙️Format:Live
📲 Set a reminder and join us!
👇 Drop a "👋" in the comments if you'll be there!
#RabiesElimination#AnimalWelfare#OneHealth#YouthAdvocacy#Webinar#VeterinaryMedicine#ShelterAndRescue
#DairyIndustry#AnimalWelfare#Cattle#AnimalWelfarePolicy#Reformthedairyindustry#UKDairy#Milk#Dairy#ForBritain
Our FULL manifesto can be found here: https://www.forbritain.uk/manifesto/
The UK government has unveiled an unprecedented plan to gradually eliminate animal testing in medical and pharmaceutical research.
The first phase will begin at the end of 2026 and will eliminate tests on mice used to develop treatments for skin and eye irritations.
Additionally, the country has committed to reducing the use of dogs and primates in laboratories by 35% by 2030, fulfilling an election promise made by the Labour Party.
Backed by £60 million, the strategy aims to promote ethical and technologically advanced alternatives that replace animal models without compromising the safety of vaccines, medicines, or pesticides.
Although animal experiments peaked in 2015 — with over 4 million animals used — advances in alternative methods had already helped reduce that number.
However, progress has stalled in recent years, so this new initiative seeks to accelerate the full replacement of animals.
Science Secretary Patrick Vallance stated, “Nobody wants to witness animal suffering,” and the new roadmap will allow governments, companies, scientists, and animal welfare organizations to collaborate on faster and more effective solutions.
Part of the investment will go to a specialized center that will integrate technology, data, and expertise to accelerate the transition to animal-free science.
🐾 Do you think Uzbekistan should implement a similar plan to reduce and replace animal testing? 🇺🇿💭
#AnimalWelfare#AnimalFreeScience#UK#AnimalTesting#ScientificInnovation#LabAnimals#ADNMascotas#AnimalNews#AnimalProtection#OneHealth☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot
Instagram | Facebook | Twitter | Sayt | Youtube.
Vitalik Buterin Donates to Thai Zoo
Ethereum co-founder Vitalik Buterin donates 10 million Thai baht (~$292,230) to Khao Kheow Zoo, Thailand. The donation, in two installments, starts December 26, 2024. Buterin and family will be adopted by the zoo. Details: Khao Kheow Zoo Announcement
#VitalikButerin#Ethereum#KhaoKheowZoo#Donation#Crypto#Blockchain#Thailand#AnimalWelfare#Charity#Adoption#Philanthropy#Zoo#MOODENG#CommunitySupport#TechForGood#EthereumCoFounder#News