Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🖼Gaza : soutien pictural
▪️Dans la bande de #Gaza, des artistes ont réalisé des fresques murales pour exprimer leur soutien à la flottille internationale Global Sumud.
Crédit vidéo : Agence Anadolu
RT en français • Osez questionner !
⏺À #Gaza, des mariés ont opté pour un moyen de transport inédit : une pelleteuse
Le couple a traversé les rues, malgré les décombres témoignant de la destruction générale dont elles ont été le théâtre.
Source : réseaux sociaux
RT en français • Osez questionner !
🫦 Algunas personas podrían encontrar perturbadoras las imágenes y videos compartidos. Se recomienda discreción.
⚠️🤔🏴☠️⚔️🇵🇸 Imágenes de la horrible masacre perpetrada por las fuerzas de ocupación contra un grupo de ciudadanos en el barrio de Beit Lahia, al norte de #Gaza.
🚨 The IOF carried out a new massacre, destroying an entire residential block above the heads of citizens on Tal Al-Zaatar in Jabalia, northern #Gaza Strip. Two martyrs have been recovered so far and there are a large amount of wounded.
Artillery shelling continues on various parts of Jabalia, and several martyrs have ascended there as a result of residential homes being targeted.
4 martyrs and 5 injuries were reported as a result of the IOF targeting of a gathering of citizens on Al-Nasr Street west of Gaza City.
Further, internet and communications have been cut off in the northern Gaza Strip as a result of the IOF aggression, as the siege enters its third week.
🚨🟢 BREAKING - Hamas leader Khalil Al-Hayya announces the martyrdom of the great leader, President of the Hamas Political Bureau, the hero of Al-Aqsa Flood, Yahya Sinwar, who sought martyrdom and attained it after clashing with a zionist force alongside other fighters in the #Gaza Strip. Further coverage of the Al-Hayya’s statement will be provided.
Glory to the martyrs.
Ahmed Al-Telbani, Director of the Central Station in the Medical Services’ Emergency and Ambulance Department, ascended to martyrdom along with his family members in the IOF air strike of their home in Maghazi camp, central #Gaza Strip.
Glory to the martyrs.
🔻 The IOF admits to the death of 5 IOF soldiers, including two officers, during a battle with the resistance in southern Lebanon. In the same incident, three Golani Brigade soldiers (including an officer) were seriously wounded. In total, the IOF admitted to the critical wounding of 8 zionist soldiers in three battles in southern Lebanon.
They also admitted to the serious wounding of a soldier during a battle in the southern #Gaza Strip yesterday.
🚨 10 martyrs have been recovered by Civil Defense crews following the IOF bombing the Al-Telbani family home in Maghazi camp in the central #Gaza Strip.
60 martyrs have ascended in the Gaza Strip today, with at least 25 of them in Jabalia camp.
On October 17th, 2023, in a cowardly assassination, commander Ayman Nofal ascended after US-funded IOF warplanes targeted him in Bureij camp in central #Gaza. Beloved by allfactions, the commanding martyr was an Al-Qassam Brigades leader who created the foundations of the united Joint Operations Room of Palestinian Resistance Factions, a room in which the spectrum of Palestinian and Arab resistance coordinate. Just weeks ago, Ayman's nephew was martyred at the Gaza border protests.
Ayman embodied the spirit of the Joint Room which he led in his words and deeds, recognizing, like martyred leaders before him, "Either we rise together, or they will kill us individually."
Here, Ayman speaks in 2021 at the Joint Operation's Room annual training for all factions. Without a doubt, Ayman was one of the engineers of the long-planned Al-Aqsa Flood for the sake of our prisoners and Al-Aqsa, evident in the words of this speech: GiladShalit was just practice. Learning from the lessons of previous operations and honoring the blood of the martyrs, we march forth towards liberation, never forgetting those who paved the path.
Glory to our martyrs! Glory to our resistance! Liberation nears with their guiding illumination.
🚨 22 martyrs have ascended in the horrific massacre at the Abu Hussein School in Jabalia camp, northern #Gaza Strip, and dozens are wounded. Most of the martyrs are children and women, after the IOF bombed the school housing a large number of displaced people.
Tanks began firing shells at the school after advancing from west of Jabalia. The hospitals in the north are unable to deal with the large number of injuries and martyrs.
The IOF also bombed the Khalifa School in the northern #Gaza Strip, resulting in a large fire and one martyr. In a series of strikes, at least 11 martyrs ascended in Gaza City. The siege of Jabalia camp and the north continues for the 13th day without any aid reaching it.