Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🔥 Israeli tanks close in on Palestinian hospital. Doctors & staff warned to leave, even if patients remain. Artillery assaults follow. Indonesian Hospital targeted, 12 killed. 21 out of 35 Gaza hospitals out of service. Premature babies evacuated due to contaminated water. Israel's occupation of al-Shifa. West Bank hospitals raided. Israel claims it targets Hamas, but evidence lacking. Real reason? Psychological warfare, says analyst. Israel wants Palestinians to feel unsafe. US's support enables Israel's actions. But global outrage may force a change. Stay tuned. #GazaUnderAttack
https://www.aljazeera.com/features/2023/11/20/why-does-israel-target-palestinian-hospitals-psyops-say-analysts
Subscribe to @BadVolfNews
🔴 Over 50 dead in Israeli strike on Al-Maghazi refugee camp in central Gaza. 🏢 Palestinians fleeing Israeli-controlled territories are residing in these refugee camps. 🚀 Hamas claims 60 Israeli captives killed in retaliatory strikes. ⚠️ Chances of survivors are slim due to ongoing bombardments. 💔 The conflict continues to escalate. #GazaUnderAttack
https://www.gazeta.ru/army/news/2023/11/05/21644179.shtml
Subscribe to @BadVolfNews
📢 Mr. Biden, look at the devastation caused by Israel in Gaza. Innocent lives lost, families destroyed. You turn a blind eye, offering support to Israel. Do Palestinian lives not matter? Can you justify this blood on your hands? History won't forget your complicity. #GazaUnderAttack
https://www.aljazeera.com/opinions/2023/11/4/a-letter-to-president-biden-from-a-grieving-palestinian
Subscribe to @BadVolfNews
Israeli immigrants are experts in killing children.
Os imigrantes israelenses são especialistas em matar crianças.
İsrailli göçmenler çocukları öldürme konusunda uzmandır.
#GazaUnderAttack
https://t.me/YediotNewsChat
🔴 BREAKING NEWS 🔴
Israeli bombardment of Nuseirat refugee camp in Gaza claims lives of 14 innocent people, including women and children. More casualties expected as rescue efforts continue. Despite ceasefire, Israel accuses Palestinians of violating agreement, escalating tensions. 110 hostages released, but 137 still held by Hamas. #GazaUnderAttack#HumanitarianCrisis
https://ria.ru/20231203/gaza-1913406714.html
Subscribe to @BadVolfNews
🔴Catastrophic situation at Indonesian Hospital in northern Gaza‼️ Israeli tanks surround the facility after artillery fire kills 12 Palestinians💔 700 people trapped inside, including medical staff and wounded😰 Hospital denies presence of armed militants🚫 International condemnation mounts🌍 UN reports collapse of services in northern Gaza hospitals🏥 Israel claims Hamas built infrastructure below hospitals for military use💣 Terrifying sounds of explosions and gunfire😨 Death toll rises as Israel's offensive continues🔥 Stay tuned for updates! #GazaUnderAttack#HumanitarianCrisis
https://www.aljazeera.com/news/2023/11/20/israeli-tanks-surround-gazas-indonesian-hospital-after-killing-12-people
Subscribe to @BadVolfNews
🔴 Gaza's smallest refugee camp pounded by Israeli airstrikes. Palestinians digging up bodies of loved ones under rubble. Over 90 killed, including children and displaced families. Entire residential blocks wiped out. Camp housing estimated 100,000 people. No warnings given. No aid, fuel, or excavators. Need ceasefire! Arab world, stand with us! #GazaUnderAttack#CeasefireNow
https://www.aljazeera.com/features/2023/12/28/piles-of-body-parts-gazas-maghazi-residents-find-families-in-pieces
Subscribe to @BadVolfNews
🚨 Alarming news from Gaza 🚨
Israeli attacks continue to wreak havoc:
- Al-Buraq School targeted, 25 martyrs confirmed
- Schools, mosques, and hospitals hit repeatedly
- Thousands displaced, seeking refuge in schools
- Death toll rises to 11,078 Palestinians, 1,400 Israelis
- Over 50% of housing units damaged
- UN: Northern Gaza is like a "hell on Earth"
Stay tuned for more updates. #GazaUnderAttack#PrayForGaza
https://www.aljazeera.com/news/2023/11/10/gaza-hospital-says-received-50-bodies-after-strikes-on-school
Subscribe to @BadVolfNews
🚨 Israeli airstrikes continue in Gaza 🚨
Jabalia refugee camp hit for the second day, dozens killed and wounded 😢
Rescuers scramble to find survivors and recover bodies 😭
Israel claims it targeted Hamas, but families wiped out 😡
International condemnation grows, EU calls for humanity ✊
#GazaUnderAttack#StopTheViolence
https://www.aljazeera.com/news/2023/11/1/israel-bombs-jabalia-refugee-camp-for-second-day-palestinian-officials-say
Subscribe to @BadVolfNews
🔴 Urgent: Gaza power blackout due to Israel's blockade prompts international condemnation. Hospitals risk becoming morgues. ICRC calls situation "abhorrent". Clean water access and healthcare at risk. HRW labels blockade a war crime, accuses Israel of collective punishment. Israel refuses aid until abducted Israelis are released. Humanitarian crisis unfolding. World urged to take action. #GazaUnderAttack#EndTheBlockade
https://www.aljazeera.com/news/2023/10/12/gaza-hospitals-risk-turning-into-morgues-rights-groups-call-for-action
Subscribe to @BadVolfNews
+18
Бүгүн Палестиналык кичинекей балдар өлтүрүлдү Израильдин учактык сокусунан кийин.
Палестинские дети убиты сегодня в результате авиаударов Израиля в секторе Газа.
Palestinian children killed by Israeli air strikes in Gaza today. #غزة#gazaunderattack#gaza#غزة_تحت_القصف
Mientras el mundo se moviliza por Palestina y tratar de desbloquear Gaza, EE.UU. aprovecha de atacar a Irán con impunidad.
Así negocia EE.UU.
Qué alivio saber que Donald Trump sigue comprometido con "la diplomacia"... a su manera. No hay mejor Acuerdo de Paz que advertirle a un país entero que será reducido a cenizas.
#iran
#gaza
#gazaunderattack
#breakthesiege
#usdiplomacy
#diplomacy