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

Резултати

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

Пребарај: #sgtogether

当前筛选 #sgtogether清除筛选
REACH

@reachsg · Post #609 · 17.08.2020 г., 09:09

"We are living in unprecedented times, but with fortitude and resilience, we can and will stand in solidarity as one united Singapore – to beat this crisis and emerge stronger as a nation." -- DPM Heng Swee Keat #SGTogether#SGUnited

REACH

@reachsg · Post #601 · 15.06.2020 г., 02:34

Catch Mr Liang Eng Hwa’s LIVE interview on Capital 95.8FM Tonight, 6.30pm! Join us in discussing the Budget, Digitalisation & Jobs and national issues! Also find out what our citizens have to say through feedback collected by REACH. Stay tuned! #SGUnited#SGTogether More: https://www.facebook.com/92744267226/posts/10157332345052227

REACH

@reachsg · Post #592 · 20.05.2020 г., 03:16

As we approach the end of the Circuit Breaker, measures will be progressively lifted in three phases from 2 June. Many restrictions in place will continue in Phase 1. #SGUnited#SGTogether.

REACH

@reachsg · Post #589 · 02.05.2020 г., 09:22

The Government announced that there will be gradual easing of Circuit Breaker measures. What are the services that will resume operation? Find out here! #SGUnited#SGTogether

URA Singapore

@URASingapore · Post #162 · 11.10.2021 г., 03:54

In our compact city, planning for the many different land use needs is often like a balancing act. By working together, we can make future Singapore a space for our hopes and dreams. We've just launched Phase 2 of the Long-Term Plan Review public engagement exercise - come share your ideas at: go.gov.sg/ltpr #LTPR2021#SGTogether

URA Singapore

@URASingapore · Post #135 · 26.07.2021 г., 09:50

💡What do you value more in shaping a liveable Singapore: a good transportation network, convenient access to amenities, greenery in the city or the other factors above? We're calling for your views and ideas in our online poll for the Long-Term Plan Review. With your participation, we can develop long-term land use plans that will better meet your needs and aspirations as well as those of future generations! Tell us more at: go.gov.sg/ltpr #LTPR2021#SGTogether

URA Singapore

@URASingapore · Post #134 · 17.07.2021 г., 05:43

📣 We just launched our public engagement for the Long-Term Plan Review (LTPR) today and are excited to develop plans for Singapore's next chapter with you over the next year! The #LTPR2021 is the latest review of plans that will steward land resources not just for today's use but also for future generations over the next 50 years and beyond. We'd love to hear your hopes and aspirations for the future to develop these long-term plans! Watch how long-term planning has shaped the everyday lives of fellow citizens as well as what they dream for our future city - and share your dreams with us in our online poll at go.gov.sg/ltpr #SGTogether

NEA Singapore

@NEASingapore · Post #65 · 15.06.2020 г., 04:00

Where there are wet and dark crevices, NEA’s Dengue Inspection Officer Marthandan will be there. Let him show you how he and his team spot and tackle mosquito breeding in the areas around you! Join him in our #NEAOfficers Story Highlight on our Instagram profile (www.instagram.com/nea_sg)! #SGUnited#SGTogether

MND Singapore

@mndsingapore · Post #172 · 01.05.2021 г., 02:14

It has been more than a year since COVID-19 happened. Many of us have had to adapt to new work situations and overcome the various challenges the pandemic brought with it. Today, we salute all workers, especially the frontliners who have been working extra hard to keep us safe this past year. Happy Labour Day! 💪🇸🇬 #SGUnited#SGTogether

MTI Singapore

@MTISingapore · Post #27 · 09.08.2021 г., 03:46

This National Day, let us celebrate the Singapore spirit that has kept us going during the most challenging of times. It will continue to help us emerge stronger for the future. Happy 56th Birthday, Singapore! #TogetherOurSGSpirit#SGUnited#SGTogether

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