TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #121 · 20 јул.

Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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

Резултати

Пронајдени 17 слични објави

Пребарај: #govsgexplains

当前筛选 #govsgexplains清除筛选
gov.sg

@Govsg · Post #3330 · 17.03.2026 г., 06:38

Tensions in the Middle East are driving global fuel prices up. #govsgexplains how this could affect you and what measures are available to help Singapore and Singaporeans navigate this period.

gov.sg

@Govsg · Post #3283 · 06.02.2026 г., 07:19

🚦Parliament passed the new Land Transport and Related Matters Bill on 4 Feb 2026. #govsgExplains four key changes in this Act that facilitate the ERP 2 transition and strengthen deterrence for active mobility and vehicular offences. More info: go.gov.sg/govsgexplains-ltrma

gov.sg

@Govsg · Post #3227 · 07.11.2025 г., 11:35

📢The Weekly Wrap – 7 November 2025 1) Wondering how Singapore is tackling online harms? The new Online Safety (Relief and Accountability) Bill (OSRA) is a comprehensive legal framework that offers better protection to victims of online harms. Here’s how OSRA will strengthen online safety👇 1) Set up the Online Safety Commission to help victims seek timely redress 2) Introduce Statutory Torts to enhance perpetrators’ accountability 3) Support victims in identifying wrongdoers 🔗 Learn more: go.gov.sg/parl-roundup-osra 2) Site of 38 Oxley Road intended to be gazetted as a National Monument The National Heritage Board’s Preservation of Sites and Monuments Advisory Board has assessed the Site of 38 Oxley Road to be of historic significance and national importance. If preserved and acquired, all private living spaces will be removed to respect Mr Lee Kuan Yew’s wishes for privacy. #govsgexplains: go.gov.sg/explains-38oxleyroad-1 ➡️ You can also read more about Mr Lee’s views on the Site: go.gov.sg/explains-38oxleyroad-2 3) Visit “We Can ACT Against Scams” Roadshow Learn ways to protect yourself and your loved ones from scams. Don’t miss the interactive activities this weekend! 🗓️ 8 & 9 Nov 2025 (Sat & Sun) 🕙 10am – 8pm 📍Toa Payoh HDB Hub Atrium 🔗 Plan your visit: go.gov.sg/antiscamroadshow

gov.sg

@Govsg · Post #3201 · 03.11.2025 г., 08:01

In its 2018 Report, the Ministerial Committee on the Site of 38 Oxley Road concluded that while Mr Lee Kuan Yew preferred the building to be demolished, he was prepared to accept other options. #govsgexplains more about the background of Mr Lee’s views on the Site of 38 Oxley Road. ⬆️

gov.sg

@Govsg · Post #3191 · 03.11.2025 г., 07:37

The National Heritage Board’s (NHB) Preservation of Sites and Monuments (PSM) Advisory Board has assessed the Site of 38 Oxley Road to be of historic significance and national importance. No other site or monument represents this foundational part of Singapore’s independence history. The Government intends to gazette the Site of 38 Oxley Road to safeguard and preserve it as a National Monument for possible use as a heritage park. If preserved and acquired, all private living spaces will be removed to respect Mr Lee Kuan Yew’s wishes for privacy. #govsgexplains more ⬆️

gov.sg

@Govsg · Post #2596 · 20.12.2024 г., 13:00

#govsgexplains: Incorrect use of NRICs has made us more vulnerable over time. However, the shift from using masked NRIC numbers does not mean automatically unmasking and using the full NRIC number in all circumstances. How can we better protect our personal data? Find out more ⬆️

gov.sg

@Govsg · Post #2563 · 15.11.2024 г., 10:25

📢The Weekly Wrap – 15 November 2024 1. Supporting our Hawkers 🍽 Hawker centres are an integral part of our daily lives. How can we support hawkers better while keeping food prices affordable? 👉#govsgexplains more: • Balancing fair incomes for hawkers while keeping food options affordable: go.gov.sg/hawkers-wrap • Decisive actions taken to support Singaporeans with their cost of living: go.gov.sg/col-support-wrap 2. Live longer, Learn for Life 📈 Are you considering a career switch but afraid to take the first step? PM Lawrence Wong shares more on how the Government can support and journey with you through SkillsFuture 💪 🔗 Find out more at: go.gov.sg/learnforlife2024 3. Managing community disputes more effectively Want to resolve disputes with neighbours faster? There are now better mediation efforts and a dedicated team to facilitate this. Say yes to good neighbourliness! 🔗 Find out more at: go.gov.sg/community-disputes-wrap

gov.sg

@Govsg · Post #2552 · 15.11.2024 г., 01:31

🔼 Find out more about the decisive actions taken to support Singaporeans with their cost of living. We stand ready to do more to address these concerns. #govsgexplains

gov.sg

@Govsg · Post #2542 · 14.11.2024 г., 12:07

How can we ensure fair incomes for our hawkers while keeping food prices affordable for everyone? #govsgexplains more ⬆️

gov.sg

@Govsg · Post #2460 · 13.09.2024 г., 08:15

Curious about why public transport fares are being adjusted? Read on ⬆️ to find out the reasons for the review and the measures in place to support you. #govsgexplains

gov.sg

@Govsg · Post #2213 · 24.05.2024 г., 10:32

In view of the heightened threat situation, Ministry of Home Affairs and Home Team Departments have stepped up patrols and security measures. 📢 With the June school holidays round the corner, please continue to stay safe and vigilant! #govsgexplains

gov.sg

@Govsg · Post #2194 · 17.05.2024 г., 04:32

Singapore has voted in favour of a resolution at the United Nations General Assembly that expresses support for the admission of Palestine as a UN member. Find out why ⬆️#GovsgExplains

12
ПретходнаСтраница 1 од 2Следна