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

Резултати

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

Пребарај: #shapes

当前筛选 #shapes清除筛选
Universe Mysteries 🪐

@cosmomyst · Post #408 · 11.10.2025 г., 18:21

🪐 The galaxy NGC 2683, sometimes called the "UFO Galaxy," has a dramatic, warped disk that gives it a shape unlike typical spirals. Located about 35 million light-years away in the constellation Lynx, its tilted, edge-on view and slightly twisted arms create the illusion of a flying saucer drifting through space, making it one of the most striking examples of galaxies with unusual forms. ✨ #galaxies⚡#shapes⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #360 · 01.10.2025 г., 22:21

🪐 The galaxy NGC 4710, located about 60 million light-years away in the constellation Coma Berenices, is famous for its strikingly thin, edge-on profile that makes it look more like a cosmic needle than a typical spiral or elliptical galaxy. This unusual "boxy/peanut-shaped" bulge is thought to form when a flat disk of stars buckles and warps over time, creating a rare structure that reveals the hidden dynamics shaping galactic evolution. ✨ #galaxies⚡#shapes⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #275 · 15.09.2025 г., 13:11

🪐 The galaxy UGC 2885, sometimes called "Rubin's Galaxy," sports an unusual appearance with its outsized, sprawling disk—nearly 2.5 times wider than the Milky Way. Its vast, faint spiral arms stretch for over half a million light-years, making it not only one of the largest known spiral galaxies but also a cosmic oddity that challenges ideas about how galaxies can grow and maintain such immense, delicate structures. ✨ #galaxies⚡#mysteries⚡#shapes⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​

Universe Mysteries 🪐

@cosmomyst · Post #342 · 28.09.2025 г., 15:21

🪐 The galaxy known as the Cartwheel Galaxy, located about 500 million light-years away in the constellation Sculptor, displays a striking ring-and-spoke structure unlike ordinary spirals or ovals. Its unusual shape was created when a smaller galaxy crashed through its center, sending waves of star formation racing outward and leaving behind bright, circular rings and faint, radial arms—an extraordinary cosmic ripple frozen in space. ✨ #galaxies⚡#shapes⚡#collisions⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #256 · 11.09.2025 г., 13:11

🪐 The galaxy NGC 1427A, found in the Fornax Cluster, looks nothing like a neat spiral or smooth oval—it's shaped like a cosmic boomerang. This odd appearance is the result of NGC 1427A plunging through the dense cluster, which causes its stars and gas to be pulled and stretched, creating a lopsided, arrowhead-like structure as it slowly gets torn apart by gravity. ✨ #galaxies⚡#shapes⚡#mystery⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​

Universe Mysteries 🪐

@cosmomyst · Post #667 · 08.02.2026 г., 12:21

🪐 Not all galaxies fit the classic spiral or oval shapes—take the galaxy LEDA 074886, located about 70 million light-years away, which stunned astronomers with its rare rectangular structure. Unlike the familiar swirls or smooth ellipses, LEDA 074886’s boxy outline is thought to be the result of a merger between two smaller galaxies, sculpting a cosmic shape almost never seen in the universe. ✨ #galaxies⚡#mergers⚡#shapes⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #568 · 19.12.2025 г., 22:21

🪐 The galaxy ESO 137-001, streaking through the Norma Cluster about 220 million light-years away, has a spectacular "tadpole" shape with long blue tails streaming out behind it. These tails are made of hot, stripped gas and young stars that formed as the galaxy plunges through the dense cluster, showing how powerful cosmic forces can stretch and reshape galaxies far beyond the classic spirals and ovals. ✨ #galaxies⚡#shapes⚡#cluster⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #323 · 24.09.2025 г., 18:21

🪐 The galaxy known as the Tadpole Galaxy (UGC 10214), about 420 million light-years away in the constellation Draco, is famous for its long, sweeping tail that stretches over 280,000 light-years. This striking "tadpole" shape was created when another galaxy passed close by, pulling out a stream of stars, gas, and dust—a cosmic encounter that gave the Tadpole Galaxy its unforgettable, bizarre silhouette among the galaxies. ✨ #galaxies⚡#shapes⚡#collision⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

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