Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
Historic Settlement: EEOC Resolves AI-Driven Age Discrimination Case
The Equal Employment Opportunity Commission (EEOC) has reached a groundbreaking settlement with iTutorGroup for $365,000 over allegations of AI-driven age discrimination. This marks the first-ever settlement against AI-powered recruitment tools in the US.
The EEOC filed the lawsuit in May 2022, accusing iTutorGroup of using an algorithm that automatically rejected older job applicants based on their age. Women over 55 and men over 60 were disproportionately affected by this automated process, which violated the Age Discrimination Act's protections for individuals aged 40 and above.
With litigation initiated in the U.S. District Court for the Eastern District of New York, the EEOC's efforts to conciliate prior to legal action were unsuccessful. As a result, the case was set for a settlement conference in October 2023. However, the EEOC has now settled the case for $365,000, underlining the significance of this legal victory.
As part of the consent decree, iTutorGroup is barred from automatically rejecting candidates based on age or gender. The company is required to adhere to non-discrimination laws and collaborate with the EEOC to establish policies that prevent unlawful discrimination in the future.
This lawsuit is likely to set a precedent for future cases involving HR Tech tools. The ongoing regulatory focus on automated employment decisions calls for responsible and compliant AI use to avoid legal consequences and uphold fairness.
#AI#Law#LegalTech#EqualOpportunity#Discrimination#AIEthics
US: New Federal Privacy Bill Aims to Safeguard Against AI-Driven Discrimination
Greetings! Senator Maria Cantwell, head of the Senate Commerce Committee, has highlighted that her introduced federal privacy bill could serve as a protective shield against discrimination fueled by artificial intelligence. Speaking at the Washington state's Future of AI forum, she underscored both the potential of AI and the necessity for "guardrails" to prevent potential risks.
Cantwell expressed concerns about AI's potential discriminatory applications, which might lead to unfair employment or loan practices. She emphasized the importance of her privacy legislation, designed to safeguard individuals from such biases.
While not providing specific details during the forum, Cantwell's spokesperson indicated that she was referring to the Consumer Online Privacy Rights Act, initially introduced in 2019 and re-introduced in 2021. The bill proposes several key provisions, including requiring companies to obtain consumers' opt-in consent for behaviorally targeted ads and prohibiting discriminatory ad targeting based on factors such as race, religion, or sex.
The legislation also aims to hold companies accountable for using algorithms in housing, education, job, or credit ads. Cantwell's advocacy reflects a growing awareness of the need to regulate AI applications to ensure fairness and protect individuals' rights.
#AI#Privacy#Discrimination#Legislation#AIEthics#Law
Lithuania Bans Property Purchases by Russians and Belarusians
The Lithuanian Parliament committee has approved a ban on Russian and Belarusian citizens buying real estate in Lithuania. Exceptions apply only to those already residing in the country, but transactions near military sites remain prohibited. This broad ban targets nationality rather than specific sanctioned individuals. Previously, Lithuania tightened rules by revoking residence permits from Russians visiting their homeland.
#Lithuania#Russia#Belarus#RealEstate#Discrimination
The main news of Russia and the world ishere.
In 1968, teacher Jane Elliott divided her students by eye color (blue vs brown) to show how discrimination works. One group was labeled “better” and given privileges. The other was treated as “worse.” Children quickly changed behavior and school performance, proving how labels and power create prejudice.
🧠👀
(Read more 1)
(Read more 2)
@googlefactss
#Psychology#SocialExperiment#JaneElliott#Discrimination#Education#History
🔴 APPEL À SOLIDARITÉ JURIDIQUE
L’association Sos Donbass recherche un avocat engagé, prêt à défendre ses intérêts gracieusement face à des cas de discrimination préoccupants.
➡️ Refus d’ouverture de compte bancaire, alors même que la loi française garantit ce droit à toute personne morale ou physique.
➡️ Fermeture arbitraire de plateformes de dons telles que HelloAsso, AssoConnect, Stripe, nous empêchant de mener à bien nos actions humanitaires.
🎯 Si vous êtes avocat ou connaissez un professionnel prêt à s’engager pro bono pour La Défense de nos droits fondamentaux, contactez-nous.
📩 [email protected]
📨message privé
🙏 Merci de partager cet appel autour de vous. Ensemble, faisons valoir la justice.
#AppelAvocat#Discrimination#SOSDonbass#DroitsFondamentaux#Solidarité#ProBono