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

Резултати

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

Пребарај: #nebula

当前筛选 #nebula清除筛选
Nothing Phone (2) | Updates

@NothingPhone2Updates · Post #484 · 09.12.2024 г., 16:44

MistOS - OFFICIAL | Android 15 | Nothing Phone (2) 📝 Details: - Version: v3.0 (Nebula) - Device: #Pong - Released: 09/12/24 ⬇️ Download: Gapps | Vanilla 📖 Changelogs: Device | Source 📔 Installation: Here 🖼 Screenshot : here 🆘 Support: Device 🏷 Tags: #AOSP#ROM#nebula#Official ✍️ Note: • Initial Android 15 • Clean flash recommended • Both Gapps and Vanilla build are available. • Dolby Atmos available. 🏆 Credits: - Chandu and drishal for DT - Hellboy for Meteoric kernel - Fabian & Hellboy for PA Glyph Implementation - Testers - laxus,devsaee and Italian style 😎 Maintainer : @Butterfingers443 x @AgBKartikey 🔔 Updates : @NothingPhone2Updates 💬 Chat : @NothingPhone2

Interesting Planet 🌍

@interesting_planet_facts · Post #1347 · 20.03.2026 г., 12:11

🌎 Giant clouds called molecular clouds are where new stars are born. These clouds, made mostly of hydrogen gas, can stretch for hundreds of light-years. The Orion Molecular Cloud Complex, one of the closest such regions, is located about 1,350 light-years from Earth and is home to thousands of young stars. ✨ #astronomy⚡#stars⚡#nebula 👉subscribe Interesting Planet 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #208 · 02.09.2025 г., 00:11

🪐 In the galaxy NGC 1999, astronomers observed a mysterious, dark patch once believed to be a dense cloud of cosmic dust blocking light. However, further study revealed this region is actually a rare "hole" in the nebula—an empty cavity punched through the glowing gas by powerful stellar winds from young, massive stars, making it a striking example of cosmic sculpting at work. ✨ #nebula⚡#phenomena⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​

Universe Mysteries 🪐

@cosmomyst · Post #16 · 29.07.2025 г., 20:51

🪐 In the Carina Nebula, the massive star Eta Carinae is surrounded by strange, expanding clouds known as the Homunculus Nebula—vast lobes of gas and dust hurled into space by a series of explosive outbursts in the 19th century. These violent eruptions have sculpted one of the most complex and enigmatic structures ever observed, with glowing filaments and mysterious hidden cavities still being revealed by the Hubble Space Telescope. ✨ #EtaCarinae⚡#nebula⚡#mysteries 👉subscribe Universe Mysteries

Universe Mysteries 🪐

@cosmomyst · Post #61 · 02.08.2025 г., 13:11

🪐 The Egg Nebula (CRL 2688) in Cygnus glows with haunting, layered arcs of dust and gas, shaped by fierce stellar winds from a dying central star. These concentric shells, illuminated by starlight scattered through dense clouds, reveal a dramatic portrait of a Sun-like star in its brief, enigmatic transition into a planetary nebula. ✨ #nebula⚡#stars⚡#transformation⚡#nasa⚡#galaxy⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries

Universe Mysteries 🪐

@cosmomyst · Post #24 · 30.07.2025 г., 00:51

🪐 In the star-forming region of the Orion Nebula, astronomers have identified "proplyds"—dense disks of gas and dust swirling around newborn stars. These proplyds are being sculpted by fierce ultraviolet radiation from nearby massive stars, their bright comet-like tails pointing away from blazing giants such as Theta1 Orionis C. ✨ #Orion⚡#proplyds⚡#nebula 👉subscribe Universe Mysteries

Universe Mysteries 🪐

@cosmomyst · Post #23 · 30.07.2025 г., 00:00

🪐 The Boomerang Nebula in the constellation Centaurus is the coldest known place in the universe, with temperatures dropping to a chilling -272°C—colder than the cosmic microwave background itself. This young planetary nebula expels gas at incredible speeds, creating a ghostly, double-lobed shape that shrouds its dying central star in frigid mystery. ✨ #BoomerangNebula⚡#coldest⚡#nebula 👉subscribe Universe Mysteries

Universe Mysteries 🪐

@cosmomyst · Post #349 · 29.09.2025 г., 20:21

🪐 The star AG Carinae, located about 20,000 light-years away, is a rare example of a "luminous blue variable"—an unstable giant star that can erupt in massive outbursts, shedding huge shells of gas and dust. AG Carinae shines millions of times brighter than the Sun and is surrounded by a glowing nebula created by its violent eruptions, making it one of the most volatile and spectacular stars in our galaxy. ✨ #unusualstars⚡#stellareruption⚡#nebula⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #187 · 25.08.2025 г., 13:11

🪐 In the center of the galaxy NGC 2392, also known as the "Eskimo Nebula," astronomers have detected fast, energetic jets of gas blasting outwards at speeds of over 200 kilometers per second. These jets, launched by the dying central star, punch through surrounding shells of glowing gas, creating intricate, layered patterns that make this nebula one of the most visually stunning and mysterious cosmic objects observed by the Hubble Space Telescope. ✨ #nebula⚡#jets⚡#emission⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​

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