Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
Albinism: a genetic condition that reduces or stops the body's melanin production, the pigment that gives color to skin, hair, & eyes. Albino people often have very light skin, hair, and eye color. It can also affect vision, causing problems like poor sight and light sensitivity.
Most people with albinism have blue, hazel, green, or light brown eyes, depending on the amount of melanin pigmentation. Some may appear to have red or violet eyes since the lack of melanin allows underlying blood vessels to show.
Their skin is more sensitive to the sun, they burn easily and have a higher risk of skin damage. Albinism is present from birth and is inherited through genes. Most have normal health and lifespan with proper care. But many face social challenges like persecution, stigma, and discrimination in different parts of the world.
🧬☀️👁️
[Read more1]
[Read more2]
[Read more3]
[Read more4]
@googlefactss
#Albinism#Genetics#Awareness#Inclusion
If you have ideas or feedback contact us:
@Googlefactss_Feedback_bot
Uzbekistan has made a historic leap in the Gender Equality and Governance Index, rising 51 positions, from 103rd to 52nd place!
This success shows real progress in women’s education, economic empowerment, and the growth of innovative IT initiatives.
We’re committed to increasing women’s participation in the IT sector. Our educational programs aim to ensure that every woman can thrive, benefiting from the accessible public services created by the state.
Uzbekistan is a country full of talented youth, and our ambitious, creative girls are at the forefront. Empowering young women in tech is a source of national pride.
By breaking down barriers, we’re opening doors for women to lead in technology. With talent, creativity, and determination, there are no limits to what can be achieved!
This achievement reflects the power of teamwork. Thanks to international organizations, private companies, and local initiatives, Uzbekistan is building an inclusive IT ecosystem driven by diversity.
Supporting women in tech is an investment in the future—one that benefits everyone.
While progress has been made, we know there’s more to do. Women remain underrepresented, especially in rural areas. We’re working to boost computer literacy and provide technology access for rural women.
Our Vision: Every woman should have the opportunity to reach her potential, be well-educated, and equipped to earn a living—maybe even lead the next tech unicorns!
By 2030, under the Digital Uzbekistan Strategy, we aim for 300,000 IT specialists, with women making up at least half of them.
Together, we can build an inclusive, innovative future, where every girl and woman can shape the digital world.
Join us in this mission! We welcome international organizations, private companies, and individuals to collaborate in empowering girls in STEM and STEAM fields.
Let’s continue working to ensure equality and diversity in every corner of Uzbekistan!
#Uzbekistan#WomenInTech#Inclusion#STEM#Innovation#Empowerment
Canada's accessible bank notes feature distinct colors for easy identification: $5 is blue, $10 is purple (and vertical!), $20 is green, $50 is red, and $100 is brown—each with large numbers and tactile dots for the blind and partially sighted. 🇨🇦💵👁️🗨
[Source]
@googlefactss
#Accessibility#BankNotes#Inclusion#Canada#Currency#VisionLoss
🤔FOOD FOR THOUGHT💭
📌 I would like to expose a situation. If your children don't learn with children with special needs at school and have never been taught that not everyone is equal, maybe you should spend 10 minutes today to explain it to them,
📌Because although they don't currently live with these children at school, they will find them in their lives for sure.
📌In light of recent events regarding the exclusion of a child with autism from attending a school trip and a child with Down Syndrome being expelled from dance class because she couldn't keep up with it, I feel the need to share this.
📌There are boys and girls that no one invites to birthday parties. There are special children who want to be part of a team but are not selected because it's more important to win than to include these children.
📌 Kids with special needs aren't weird , they just want what everyone wants: to be accepted!
📌Can I ask a question? Is there anyone willing share this article like I did, for all the special children out there?
📌Please teach your children to be kind to these beautiful children!
📌Everyone needs love and kindness
#inclusion#syndromedown#autism#beingdifferentlynormal#respect#love#empathy@HeathSafetyTps
Grayscale Launches Dogecoin Trust
🚀 Grayscale Investments has launched the Grayscale Dogecoin Trust, redefining DOGE from a meme to an investment asset. The trust aims to offer accredited investors direct exposure to DOGE, highlighting its accessibility, low cost, and quick transactions. Grayscale's initiative underscores DOGE's role in promoting financial accessibility, as noted by Rayhaneh Sharif-Askary. While regulatory approval for secondary market trading is pending, the outlook for crypto ETFs remains positive following recent approvals. The DOGE Trust could potentially convert into an ETF in the future, aligning with the SEC's evolving view on cryptocurrencies. Notably, Bitwise Investment Advisers has proposed a Dogecoin ETF. 📈
#Grayscale#Dogecoin#Crypto#ETF#Finance#Investment#SEC#Regulation#AssetManagement#Bitwise#Inclusion#FinancialAccessibility#Meme#Blockchain#Trends#Markets#Innovation#DigitalAssets#SpotETFs#InvestmentTrusts