Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🇵🇸 This is not just a Palestinian corpse.
Today's situation in Palestine is the result of the betrayal of all Islamic countries. No one attacks a child who has a guardian. Palestine is alone. This is not just a Palestinian corpse. I see the dead bodies of the Zionist governments of Turkey, Pakistan, Afghanistan, Saudi Arabia, Egypt, with Salafi, #Wahhabi, and #Deobandi#Brotherhood ideas.
https://t.me/YediotNewsChat
Graduates of #Deoband and #Wahhabi schools killed 12 people last night.
In the terrorist attack on a police station in the Sistan region of Iran, 12 people were martyred and many were injured.
The headquarters of the Jaish-ul-Adl terrorist group is in #Pakistan. They have been taught to be kind to infidels, but if you kill 5 Muslims, you will go to heaven. The funds of these groups are provided by America and Israel. Pakistan is a breeding ground for #Sunni terrorists.
https://t.me/YediotNewsChat
The picture of the dead body of one of the #Sunni terrorists who invaded Iran's border post last night. They were wearing the uniform of the Iranian military forces.
The rest of the #Wahhabi terrorists fled to Pakistan. They hide in the deserts of Pakistan for the next surprise attack on Muslims.
Pakistan is the center of production of Wahhabi terrorists. The Wahhabis came to power in #Saudi_Arabia in 1922 by the #British.
https://t.me/YediotNewsChat
Saya mencari di Telegram dan melihat #Wahhabi (ISIS) sangat aktif di Telegram dan memiliki banyak saluran.
Banyak Muslim mengikuti Wahhabisme. Pusat pemikiran menyimpang ini adalah Takfiri di Arab Saudi. Negara-negara Arab mempunyai jumlah penduduk yang sedikit, namun mempunyai sumber daya minyak yang banyak. Mereka menjual emas hitam (minyak) dengan harga murah dan membeli barang-barang berbahan minyak dengan harga tinggi.
Konsumerisme; Peniruan terhadap Barat adalah hal biasa di kalangan umat Islam. Karena maraknya media #Zionis, ketidaktahuan dan takhayul telah menyebar di negara-negara Islam. Pemerintahan mereka lebih bersifat diktator dan bukan demokrasi. Penguasa mereka hanya meninggalkan kekuasaan ketika mereka sudah mati.
Persahabatan Muslim dengan Yahudi dan Kristen dilarang dalam Al-Qur'an; Namun para penguasa Arab berteman dengan non-Muslim dan berdansa dengan mereka. Mereka menghunus pedang melawan umat Islam dan membunuh saudara-saudara mereka. Pemikiran menyimpang ini berakar pada abad pertama Hijriah.
Abu Bakar dan Umar juga mengganggu keluarga Nabi. Allah berfirman dalam Al-Qur'an, Surat Shuri: Wahai kaum muslimin, berbuat baiklah terhadap keluarga Nabi, namun kaum muslimin membantai seluruh keluarga Nabi. Pemikiran liar yang terlihat di negara-negara Islam saat ini adalah akibat dari kudeta yang dilakukan Abu Bakar dan Omar terhadap penerus Nabi (Ali).
Teroris seperti bin Salman bin Laden, Saddam dan #Erdogan diperkenalkan sebagai tokoh utama dunia Islam. Orang-orang munafik yang diam-diam bekerja sama dengan Zionis namun menyerang umat Islam di Palestina, Irak, Lebanon, Suriah, Iran dan Yaman.
Pemerintah #Arab_Saudi, #Turki, Bahrain, Kuwait, Qatar, Mesir, Yordania, Pakistan dan Afghanistan dengan mempromosikan ide-ide menyimpang seperti Ikhwanul Muslimin dan Wahhabisme; Deobandi berperang dengan negara-negara yang ingin merdeka (Yaman, Palestina, Suriah, Irak dan Iran).
Orang-orang yang berjalan di jalan tiba-tiba meledak. Karena beberapa Wahhabi meledakkan diri mereka sendiri untuk masuk surga!!!!
Semoga Tuhan mengutuk Israel, US, dan pendukungnya. Karena mereka menghitamkan wajah Islam dan menampilkan Islam yang diinginkan US.
https://t.me/YediotNewsChat
The first Wahhabi terrorist captured by the Artsakh defense forces of Armenia.
#Azerbaijan President #Alif and #Erdogan in #Turkey denied the presence of ISIS terrorists in the war with #Armenia.
This #Wahhabi gunman confirms that he was trained by the Turkish military and was sent to Artsakh by Turkey with the promise of $2,000. According to his confessions, about 200 other terrorists were fighting with him on the same front against the Armenian forces.
He says that a total of 2,000 Wahhabi terrorists were sent to the battle lines with the defense forces of Artsakh to strengthen the Azerbaijani army.
He says: He has been ordered to cut off the heads of Armenians, and for each head he cuts off, he receives an extra hundred dollars.
https://t.me/YediotNewsChat
#Saudi_Arabia opens the first liquor store
Reuters and France news agencies claimed that the Kingdom of Saudi Arabia is preparing to open the first liquor store in the city of Riyadh.
According to the document, a copy of which was seen by Reuters, customers must register through a mobile app and after receiving a code from the State Department, they can purchase their monthly quotas at a special store.
Saudi Arabia is the largest #Wahhabi center in the world. They pay for Wahhabi schools in #Pakistan, #Afghanistan by selling oil. Graduates of these schools join #terrorist groups such as al-Qaeda, Taliban, #Daesh, Al-Nusra, Jaish al-Adl and blow themselves up among other Muslims to go to heaven. Mohammed bin Salman, the leader of Saudi Arabia, follows the path of Atatürk in #Turkey. Drinking alcohol is forbidden in Islam.
https://t.me/YediotNewsChat
The name of this religious school is "Darul Uloom #Deoband".
This huge place is located in India. #Zionists pump deviant Islamic thoughts day and night and produce thousands of terrorists. After graduation, they join terrorist groups like #Taliban, #Al-Qaeda, #ISIS. #Mufti, #Maulvi and #Mamusta are taught that if you kill 5 Muslims, you will go to heaven.
What is the result of these schools? Have they been able to improve the critical situation of #Afghanistan and #Pakistan? Graduates of these schools spread war, poverty and ignorance among Muslims.
Did #Hindus who worship cows and burn Muslims alive set up these schools for the growth of Islam? Did the Hindus unite with Islam or did they establish it to fight between Islamic groups? Why don't these groups (Deobandi, #Salafi, #Wahhabi) fight with USA and Israel?
https://t.me/YediotNewsChat