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

Резултати

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

Пребарај: #urbandesign

当前筛选 #urbandesign清除筛选
URA Singapore

@URASingapore · Post #1083 · 20.12.2024 г., 10:00

Does this vibrant walkway look familiar? Once just a canal, it's now a bustling pedestrian mall along Orchard Road! Open spaces, art installations, and alfresco dining showcase how urban design transforms infrastructure into lively community hubs. Uncover more behind-the-scenes stories about how urban design has shaped Singapore over the last 50 years 👉🏻go.gov.sg/UDPlanstoRealityTG #UrbanDesign

Hashtags

URA Singapore

@URASingapore · Post #919 · 03.08.2024 г., 02:00

🤔 Have you seen this staircase at Upper Thomson Road on your social media feed? More than just a photogenic spot, it is the result of a community effort led by Joanne Teh, a resident at Yew Lian Park, who wanted to make the pathway safer and more attractive for everyone to use and enjoy. If you have an idea to enhance and enliven the spaces around you, apply to get up to $20,000 from the Lively Places Fund for your initiatives! Find out more 👉go.gov.sg/LivelyPlacesFundTG #UrbanDesign#LivelyPlacesFund

URA Singapore

@URASingapore · Post #910 · 24.07.2024 г., 10:00

Singapore’s hot weather can be a bother if you take a stroll at Marina Bay. But with our solar-powered breeze shelters strategically placed along the promenade, you don’t need no Oppas to shelter you from the heat! 🌬 #UrbanDesign#DiscoverSingapore#MarinaBay

URA Singapore

@URASingapore · Post #905 · 11.07.2024 г., 10:30

A bunch of postcards just arrived in the mail for you! 💌 We’re working on a Recreation Master Plan to make way for more leisure opportunities. For the Central Area of Singapore, there are plans to enhance the attractiveness of the community space at Sultan Gate, improve the walk-cycle connectivity along the Inner Ring Corridor and more! Want to help shape these spaces and other recreational spots in this region? Share your best ideas with us here: 👉go.gov.sg/CentralAreaRecreTG #DMP2025#RecreaMP#ExploreSingapore#Recreation#UrbanDesign#SpaceForOurDreams

URA Singapore

@URASingapore · Post #1428 · 06.12.2025 г., 10:00

Love the vibes at Holland Village? We do too 🙌 From low-rise buildings to continuous walkways and elegant signages, find out how we’re retaining the unique charm and familiar identity of the area through thoughtful planning and design. #HollandVillage#ExploreSingapore#UrbanDesign#IdentityNode#SGHeritage

URA Singapore

@URASingapore · Post #947 · 12.09.2024 г., 04:15

Can you picture a car-lite future for Singapore? With more cycling paths being built, it could soon be a reality! The Bishan-to-City (B2C) Link is one of the pathways made possible by planners like Syafie, along with feedback from citizens like you, to make the island more connected and accessible for everyone. Watch on to learn more about his role and why he loves it. Want to shape our city too? Explore career opportunities with URA now 👉http://go.gov.sg/URA-CareersSyafieTG Also, learn more about our efforts to create a car-lite and sustainable city on our free guided community tours: http://go.gov.sg/ura-wcfd24 #UrbanDesign#URASingapore#DiscoverSingapore#Hiring#UrbanPlanning#WCFDsg#WorldCarFreeDay

The Shanghai Lingang Special Area master plan. Design: Ennead Architects Location: Shanghai, China Ennead Architects has designed the Shanghai Lingang Special Area master plan (a new hub for global commerce) around the central axis that defines the Dishui Lake district in Shanghai. One of the key features of the Shanghai Lingang Special Area will be “The Ring”. This circular, cantilevered observation deck, and museum will afford 360-degree views of nearby Dishui Lake, Shanghai and the Pacific Ocean. The two towers flanking the Ring (The Tower Waterfall and Tower Rhomboid) are designed to become two of the most easily recognizable features of the new business district. Similar in scale, the towers have distinct identities. #Architecture#arch_shovel#NewsArchitecture#News#Shanghai#China#Masterplan#CityPlanning#OfficeBuilding#CommercialArchitecture#UrbanDistrict#UrbanDesign