Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
G20 leaders pledge support for Afghanistan
The Group of 20 major economies is determined to tackle the humanitarian crisis in Afghanistan, even if it means having to coordinate efforts with the Taliban, Italian Prime Minister Mario Draghi said after hosting an emergency summit.
#News#Reuters#Taliban#Afghanistan
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
WARNING: GRAPHIC CONTENT - Taliban will step up mosque security after attacks
Large crowds of people gathered in the Afghan city of Kandahar to bury victims of an Islamic State suicide attack on worshippers as Taliban pledged to step up security at Shi'ite mosques
#News#Reuters#Taliban#Mosque
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Afghans seeking travel papers crowd passport office
Crowds of Afghans flocked to the passport office in Kabul desperate to get travel documents
#News#Reuters#Taliban#Afghanistan#Passports
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Future at stake for Kabul orphanage
The program director at a large Kabul orphanage says he is cutting back on the amount of fruit and meat he gives the children each week because the home is running out of money
#News#Reuters#Kabul#Taliban#Orphanage#Afghanistan
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
The oldest known use of oil paint was found in caves behind the Buddhas of Bamiyan in Afghanistan, dating to the mid-7th century AD. Artists used walnut and poppy seed oils to bind mineral pigments. The giant Buddhas were destroyed by the Taliban in 2001. The murals show Buddha scenes and reflect influences from China, India, and Eurasia, linked to Silk Road artists.
[Read more]
@googlefactss🎨🕌
#Afghanistan#OilPaint#Bamiyan#Taliban#SilkRoad#ArtHistory
The situation at our Blue Mosque in #MazarESharif is deeply disturbing and demands immediate action - @nytimes.
This is not merely a building — it is a vital part of our shared religious and civilisational heritage.
We call on the #Taliban regime to fulfil its primary responsibility: to commission Afghan and international experts and allocate public funds for urgent repairs.
Afghan political and business leaders must also contribute. My colleagues and I will certainly do our part. 🤝
We urge #UNESCO to give this restoration and conservation the highest priority.
Finally, we appeal to our neighbours — especially #Uzbekistan🇺🇿, #Iran🇮🇷, and #Türkiye🇹🇷 — to support this effort with their technical expertise and resources.
@president_uz@HakanFidan@araghchi
@unescowhc
#MazarESharif#CulturalHeritage#SaveBlueMosque
The Qur'an tells Muslims to be kind to each other, but to treat the infidels harshly. While Muslims do exactly the opposite of what God said.
#Turkey attacks the Muslims of Iraq, Syria and Libya, but has political, economic and military relations with USA and Israel.
#Saudi_Arabia, #Qatar, the United Arab #Emirates (Wahhabi) attack Palestine, Syria, Yemen and Lebanon, but they have deep friendly relations with the USA and Israel.
#Taliban (Wahhabi) terrorists are attacking Pakistan. Terrorists from #Azerbaijan and #Pakistan are attacking Iran. Iraq invades Kuwait.
#Egypt and #Jordan surrounded Palestine, but they have good relations with Israel and USA.
All regional governments must be destroyed, traitors like Erdogan must be overthrown.
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
October 11, 2021: Alaska quake, U.S. and Taliban, AstraZeneca, Prince Andrew, California oil spill
October 11, 2021: Alaska quake, U.S. and Taliban, AstraZeneca, Prince Andrew, California oil spill
1. An earthquake of magnitude 6.8 struck the Alaska Peninsula region, the European Mediterranean Seismological Centre said.
2. The United States said on Sunday the first face-to-face meeting between senior U.S. and Taliban officials since the hardline group retook power in Afghanistan was "candid and professional" and that the U.S. side reiterated that the Taliban would be judged on their actions, not just their words.
3. AstraZeneca's experimental COVID-19 drug has helped cut the risk of severe disease or death in a late-stage study, the British drug maker said, a boost to its efforts to develop coronavirus medicines beyond vaccines.
4. British police said they would be taking no further action after conducting a review of evidence relating to sex crime allegations against Queen Elizabeth's son, Prince Andrew, and the late U.S. financier Jeffrey Epstein.
5. Beaches in a southern California city that were shut because of an oil spill last week are set to reopen, authorities said in a statement.
#Alaska
#Earthquake
#UnitedStates
#Taliban
#Afghanistan
#AstraZeneca
#Covid19
#UnitedKingdom
#BritishPolice
#PrinceAndrew
#Epstein
#QueenElizabeth
#Headlines
#MorningNews
#Business
#News
#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
October 11, 2021: Alaska quake, U.S. and Taliban, AstraZeneca, Prince Andrew, California oil spill
October 11, 2021: Alaska quake, U.S. and Taliban, AstraZeneca, Prince Andrew, California oil spill
1. An earthquake of magnitude 6.8 struck the Alaska Peninsula region, the European Mediterranean Seismological Centre said.
2. The United States said on Sunday the first face-to-face meeting between senior U.S. and Taliban officials since the hardline group retook power in Afghanistan was "candid and professional" and that the U.S. side reiterated that the Taliban would be judged on their actions, not just their words.
3. AstraZeneca's experimental COVID-19 drug has helped cut the risk of severe disease or death in a late-stage study, the British drug maker said, a boost to its efforts to develop coronavirus medicines beyond vaccines.
4. British police said they would be taking no further action after conducting a review of evidence relating to sex crime allegations against Queen Elizabeth's son, Prince Andrew, and the late U.S. financier Jeffrey Epstein.
5. Beaches in a southern California city that were shut because of an oil spill last week are set to reopen, authorities said in a statement.
#Alaska
#Earthquake
#UnitedStates
#Taliban
#Afghanistan
#AstraZeneca
#Covid19
#UnitedKingdom
#BritishPolice
#PrinceAndrew
#Epstein
#QueenElizabeth
#Headlines
#MorningNews
#Business
#News
#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖