Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
烏克蘭人面對困境,都不忘支持香港人!
佢寄語香港人要奮戰到底,終有一日可將中國驅逐出香港!"Hong Kong is not China in the same way that Ukraine is not Russia. It never has been. We will fight until the last man.", says the director of the Association of Ukrainians in Great Britain.
Despite the toughest moment of Ukrainian, they still stand with Hongkongers.
He told us, we shall keep fighting, China must then be expelled from Hong Kong one day.
#StandwithUkraine#StandwithHongkong
@UkrClubDniproMcr
UN Alarm: Hong Kong's Freedoms Under Severe Threat
UN Chief Guterres' report reveals:
• Activist Chow Hang-tung arbitrarily arrested
• Threats of criminal charges for discussing ongoing cases
• Death threats against Jimmy Lai's family and lawyers
Key concerns:
- Potential criminal liability for UN cooperation
- Attacks on legal representation
"We won't be silenced," says Sebastian Lai, Jimmy's son.
UN Human Rights Council to discuss during 57th session (Sept-Oct 2023).
World's response crucial as Hong Kong's autonomy erodes.
#StandWithHongKong#PressFreedom#UNReport
The HKDM team wish everyone a happy new year! We wish that all of us will continue fighting until our Hong Kong is back!
#fightforfreedom#standwithhongkong#HKDMovement
Due to China's increasing influence and the implementation of a new national security law, Hong Kong's economic position has been severely shaken. The erosion of the city's autonomy and the tightening grip of Chinese authorities have raised concerns among international businesses, leading to a decline in investments and a loss of confidence in Hong Kong as a global financial center. This, coupled with the redirection of cargo and the restructuring of shipping routes, has further diminished Hong Kong's economic prospects.
https://www.rfa.org/cantonese/news/hk-link-04042024161154.html
#ChinaInfiltration#NSL#freeHK#standwithhongkong
Wish everyone a happy Lunar New Year! Bring glory back to Hong Kong in the year of dragon!
#HKDMovement
#glorytoHongKong
#lunarnewyear
#standwithhongkong
監獄規則修訂 引發強烈憂慮
香港政府最新修訂《監獄規則》,容許懲教署以「維護國安」為由,限制律師、宗教人員與在囚人士接觸,立即生效,卻延至 7 月 23 日才提交立法會審議。
此舉可能完全封鎖數以千計的政治犯與外界聯繫。外界無從得知港府在囚室內的行為,尤其中懲教機構推行「思想重整」計劃,更有年輕囚犯曾透露遭受性侵犯。
這不是安全措施,是孤立、是剝奪。
Prison Rule Changes in Hong Kong Spark Alarm
The Hong Kong government’s new amendments to prison rules now permit correctional authorities to restrict inmate access to lawyers and religious staff for “national security” reasons. Though enacted on July 18, the changes won’t face legislative review until July 23.
This effectively blocks thousands of political prisoners from contacting the outside world. The public may never know what happens behind prison walls—especially as reports emerge of indoctrination programs and teenage inmates alleging sexual abuse.
This isn’t about security. It’s isolation, erasure, and silencing.
#silencingHongKong#NSL#PoliticalPrisonersHK#StandWithHongKong
《Harbour of Freedom First Issue》 Excerpt
Race to Campaigns overseas in Aug-Sep
Please download the full version of the first issue on Google drive
PDF(CN):
https://drive.google.com/file/d/1Vms9WnuNSoJtPOLOxf32ONYYZCKo6ULL/view?usp=sharing
PDF(ENG):
https://drive.google.com/file/d/1Qya_BexfjcfehxghTLVOpXteuXVwA-w-/view?usp=sharing
#國際戰線#HongKong#StandwithHongKong
#香港#抗爭#反送中
Tse Wai-chun’s Parting Shot: Too Little, Too Late,
In a jaw-dropping farewell speech, pro-#Beijing lawmaker Tse Wai-chun compared #HongKong’s 1997 handover to the Soviet Iron Curtain, the Khmer Rouge massacres, and #Nazi concentration camps.
He didn’t stop there. Tse mocked “panda tours” and “red tourism” as “neither authentic, nor unique,” and bizarrely called for “colonial tourism,” insisting even tea stains on old Yixing teapots should be preserved.
But let’s not be fooled. For years, Tse voted in lockstep with Beijing’s agenda, opposing the will of #Hongkongers. From suppressing democratic reforms to backing draconian laws, his record is clear. Now, as rumors swirl that he’s been cast aside by the very establishment he served, he suddenly speaks out?
This isn’t courage. It’s convenience.
Tse’s last-minute theatrics don’t erase years of complicity. Hongkongers deserve leaders who stand with them when it matters—not just when the political winds shift.
#FreeHK#StandWithHongKong