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

Резултати

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

Пребарај: #djangocon

当前筛选 #djangocon清除筛选
djangoproject

@djangoproject · Post #591 · 29.03.2018 г., 06:56

https://2018.djangocon.us/ Six days of talks, sprints, and tutorials in San Diego October 14-19 2018 #DjangoCon US has something for everyone, from the person who develops Django applications for a living to the person who just tinkers in their spare time. You'll discover details about a range of diverse applications that people from all over the world are building with Django, get a deeper understanding of concepts you’re already familiar with and discover new ways to use them, and have a lot of fun!

Hashtags

djangoproject

@djangoproject · Post #590 · 29.03.2018 г., 06:46

https://2018.djangocon.eu/ #DjangoCon Europe 2018 in Heidelberg May 23-27, 2018 · Heidelberg, Germany We are trying very hard to make this conference enjoyable to you even before it has started. One of the things we hope will be helpful is this timeline. Please understand that this is a rough timeline – as we cannot see into the future, some things might move around, but we will communicate every noticable change in a blog post!

Hashtags

djangoproject

@djangoproject · Post #371 · 04.07.2017 г., 14:47

https://2017.djangocon.us/news/tutorial-announcement/ #djangocon 🔹From 0 to 100 in Django 🔹How to React the Right Way (Django + React) 🔹Catching Tweets with Django + Django REST Framework 🔹Build a GraphQL API Using Django 🔹Build and Launch a Website on Wagtail, in Three Hours! 🔹Don’t Touch That Dial! An Introduction to Channels

Hashtags

djangoproject

@djangoproject · Post #370 · 04.07.2017 г., 14:18

https://2017.djangocon.us/ #djangocon Six days of talks, sprints, and tutorials by the community for the community. August 13–18 2017 🔸Flourishing FLOSS: Making Your Project Successful (Anna Ossowski) 🔸Functional Programming in an Imperative World. Maybe (Derik Pell) 🔸Understanding JavaScript Libraries via React and the React Ecosystem (Andrew Pinkham) 🔸Becoming a Polyglot: Lessons from Natural Language Learning (Rebekah E. Post) 🔸The Shy Person’s Guide to Tech Conferences (Ed Rivas) 🔸The CoC Committee Is Here for You (Erik Romijn) 🔸hunter2: A Symphony of Password Horror (Lilly Ryan) 🔸Files in Django (Josh Schneier) 🔸Programming Post-Progeny: A New Parent’s Perspective (Jacinda Shelly) 🔸Don’t Use My Grid System (Or Any Others) (Miriam Suzanne) 🔸Butter Smooth, Interactive Applications with Django and Websockets (Ganesh Swami) 🔸The 10 Commandments of Community Organizing (Jennifer Wadella) 🔸Exhausted Octopus Learns a Thing!! (Laura R. Webb) 🔸The Denormalized Query Engine Design Pattern (Simon Willison) 🔸Tasks: You Gotta Know How to Run ‘Em, You Gotta Know How to Safe ’Em (Filipe Ximenes)

Hashtags

djangoproject

@djangoproject · Post #369 · 04.07.2017 г., 14:08

https://2017.djangocon.us/ #djangocon Six days of talks, sprints, and tutorials by the community for the community. August 13–18 2017 🔸Saved You a Click (Or Three): Supercharging the Django Admin with Actions and Views (Liam Andrew) 🔸Django vs Flask (David “DB” Baumgold) 🔸End-to-End Django on Kubernetes (Josh Berkus) 🔸Going Rogue: How Code.org Created a Curriculum Development Platform without their Engineers (Josh Caldwell) 🔸Overcoming the Challenges of Mentoring (Kim Crayton) 🔸Stumbling Through Django and How Not to (Melanie Crutchfield) 🔸Maybe Not the Programmers They Deserved, but the Programmers They Needed (Jessica Deaton and Megan Will) 🔸GraphQL in the Wild (Arianne Dee) 🔸Accessibility Matters: Creating a Better Web (Lindsey Dragun) 🔸Taking Django Distributed (Andrew Godwin) 🔸The Monster on the Project (Tiberius Hefflin) 🔸Python & Spreadsheets: 2017 Edition (Kojo Idrissa) 🔸Type UWSGI; Press Enter; What Happens? (Philip James) 🔸Serverless Django (Rich Jones) 🔸Live long and refactor :vulcan_salute: (Sana Javed) 🔸Preventing Headaches with Linters and Automated Checks (Flávio Junior) 🔸Autopsy of a Slow Train Wreck: the Life and Death of a Django Startup (Russell Keith-Magee) 🔸The Beauty of ViewSets in Django Rest Framework (Buddy Lindsey, Jr.) 🔸Getting the most out of Django’s User Model (Julia M Looney) 🔸Alexa… (Heather Luna aka Heats) 🔸Write an API for Almost Anything (Or The Amazing Power and Flexibility of Django Rest Framework) (Charlotte Mays) 🔸The Power :zap: and Responsibility :sweat: of Unicode Adoption :sparkles: (Katie McLaughlin) 🔸Practical Unit Testing in Django (Wayne Merry) 🔸Using Django, Docker, and Scikit-Learn to Bootstrap Your Machine Learning Project (Lorena Mesa) 🔸Get a Jumpstart on Collaboration and Code Review in GitHub (Katherine “Kati” Michel) 🔸Why Can’t Everyone Just Do What I Want Them To? Leadership, Management, and Working with People Who Don’t Think like You (Briana Morgan)

Hashtags

djangoproject

@djangoproject · Post #368 · 04.07.2017 г., 13:39

http://2017.djangocon.com.au/ #DjangoCon AU: August 4, 2017 #PyCon AU: August 5 - 6, 2017 Sprints: August 7 - 8, 2017 🔷Django and JavaScript: A long and complicated friendship 🔷Bowerbirds of Technology: Architecture and Operations at Less-Than-Facebook Scale 🔷Loop better: a deeper look at iteration in Python 🔷Oh, I Found a Security Issue 🔷Offline Django with Service Workers 🔷hunter2: A Symphony of Password Horror 🔷Multitenant applications: how and why 🔷Horrors of Distributed Systems 🔷Red User, Blue User, MyUser, auth.User