Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
The Kennedy Center Would Limit Voting to Trump-Appointed Trustees
The Kennedy Center reportedly adopted bylaws earlier this year that would limit voting to Trump-appointed trustees – a controversial move that appears to reveal the long-held plan to install Trump’s name to the center.
The bylaws, in a possible breach of the institution’s charter, were revised in May and specified that board members appointed by Congress, known as ex-officio members, could not vote or count towards a quorum, according to the Washington Post.
The new rule was in force when the board voted unanimously on 18 December to add Trump’s name to the center, rebranding the building as the Trump and the JFK Memorial Center for the Performing Arts.
The name change has since triggered a wave of protests. Artists have cancelled bookings and members of Congress have vowed to overturn the name change.
Joyce Beatty, a Democrat from Ohio, is even suing to reverse it on the grounds that changing the center’s name requires an act of Congress.
Trump took over as chair of the board in February, quickly purging sitting members, while installing his supporters – including his longtime foreign policy adviser Ric Grenell, whom he appointed as president of the center.
Grenell had been a vocal tribune of Trump’s “America First” ideology, and was not afraid to ruffle feathers during past spells as ambassador to Germany and acting director of national intelligence (he was the first openly gay person to lead the intelligence community).
Just prior to his Kennedy Center appointment, Grenell served as the president’s envoy for special missions, and was involved in securing the release of Americans detained in Venezuela.
The center lists 34 presidentially appointed board members and 23 ex-officio members, who by law must include the mayor of Washington DC, head of the library of Congress, and the majority and minority leaders of the Senate.
The federal law underpinning the center’s establishment identified ex-officio members as among the venue’s trustees, charged with maintaining it as a memorial to John F Kennedy, the Post reported.
Roma Daravi, the center’s vice-president for public relations, told the Post that the rules had been changed in line with longstanding convention that ex-officio members did not vote:
“The bylaws were revised to reflect this longstanding precedent and everyone received the technical changes both before the meeting and after revisions.”
Daravi continued: “Some members attended in person, others by phone, and no concerns were voiced, no one objected, and the bylaws passed unanimously.”
Ellen Aprill, a legal scholar at UCLA, told the paper that such voting right limits breached the center’s charter.
“Clearly the intent of the charter provisions was to entrust Kennedy Center guidance to a broad group, not just those appointed by the president,” she said.
The disclosure comes as new figures showed a sharp fall in television ratings for this year’s Kennedy Center honors awards.
A record low audience of 3.01m watched this year’s broadcast of the annual honors awards – hosted by Trump himself – when it was screened by CBS, marking a stark 25% downturn from last year.
The event included appearances from some of Trump’s favorite artists, including Gloria Gaynor, Kiss and George Strait.
As artists cancel bookings, Trump on social media on Tuesday posted a string of statements from supporters criticizing the Kennedy family’s supposed lack of support for the center.
His posts on his Truth Social network started mere hours after the Kennedy family announced the death of Tatiana Schlossberg, JFK’s granddaughter, who died aged 35, from leukemia.
#kennedy#center#limit#trump#trustees
📱American Оbserver - Stay up to date on all important events
🇺🇸