Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
Ørsted Gardens.
Ørsted Gardens transformed a dilapidated building (see third image) into a new social space with semi-private decks for the individual residents.
Ørsted Gardens by Tegnestuen Lokal – "If we want to achieve a sustainable future, we cannot rely on only building sustainable buildings going forward. We need to have a visionary method of transforming and adapting existing buildings to meet our changing needs. Ørsted Gardens is an example of a project that brings a generic renovation to a new level, improving the visual and social environment for residents and visitors alike."
#arch_shovel#architecture#archdaily#facadedesign
3XN Architect’s proposal for SRPJ in Tokyo.
The design for The Shibuya Upper West project, 𝗧𝗵𝗲 𝗪𝗮𝘃𝗲𝘀, began from the inside out – understanding the target user groups, identifying key project aspirations for this new ecosystem nestled within Shibuya and Tokyo, and ensuring a clear, uncomplicated method of articulation that amplifies the spatial qualities within, without compromising the functionality and efficiency of a retail development.
Taking cues from nature as a means of creating balance between the more hard edge, urban environment of Shibuya, the simple massing articulation, or gesture mimics the pattern of waves and their undulating movement, with imagery that also evokes the contemplative and soothing gestures of raked brush strokes seen in tranquil rock gardens, evoking a sense of calm and excitement, easily recognisable and yet able to stand apart from the surrounding context.
Huge congratulations to Snohetta for their winning design!
#3xnarchitects#tokyo#facadedesign #facade#arch_shovel
‘Where’s House Warehouse’ by pbm Architects defies typical warehouse stereotypes with an ethereal design in Bangkok. The architects crafted a multi-use space blending office and storage functions. Its facade, made of glass cuboids, breaks the monotony of industrial contexts. The concept evolved from merging living, working, and storage areas seamlessly, fostering interaction and fluidity.
Architecture: PBM Architects
Images: Spaceshift Studio
📍Bangkok, Thailand
.
#facadedesign#glassarchitecture#thaiarchitecture#industrialarchitecture#arch_shovel
Facades for the OPPO Super Flagship Store.
Bamboo inspired the facade design for the OPPO Super Flagship Store in the city of Guangzhou.
An important source of food, clothing, housing, and transportation for people in Guangzhou in ancient times, the design adds a contemporary twist to the vernacular architecture of the city.
Photos: CreatAR images
Architecture: UnStudio
#unstudio#benvanberkel#materialmonth#architecture#facadedesign#arch_shovel
Do you know how many silver spheres are on the facade of the Hanjie Wanda Square in Wuhan, China?
42,333.
While they all may look identical, their specific positions involving each other recreate the effect of movement and reflection in water or the sensuous folds of silk fabric.
Photos: Edmon Leong / UNStudio
#unstudio#facades#facadedesign#architecture#retaildesign#lightingdesign#arch_shovel
From cotton to culture - Oscar Niemeyer Sphere - Baumwollspinnerei.
#leipzig#visitleipzig#architecturephotography#minimalism#facadedesign#archidaily#arch_shovel
Can you guess what inspired Unstudio architecture’s design for the facade elements of the Shenzhen Maritime Museum?
Comment your answer below!
#unstudio#ceramicdesign#facadedesign#worldmuseums#museumsoftheworld#museumdesign#architecture#architecturaldesign#arch_shovel