Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🔄Gamma: сrea presentaciones en solo unos clics con IA
La reciente actualización del servicio de creación de presentaciones impulsado por IA, Gamma, ha ampliado sus capacidades: ahora genera no solo texto e imágenes, sino también tablas con gráficos, convierte diapositivas en tarjetas para redes sociales y te permite elegir entre ilustraciones originales además de imágenes generadas por IA.
¿Cómo crear una presentación en Gamma?
1️⃣ Ve al sitio web de Gamma,haz clic en "Start for Free" y regístrate.
2️⃣Haz clic en "Create New AI" y elige una de las opciones para generar tu presentación: basada en tu esquema, completamente generada por IA o cargando una presentación existente para editarla.
3️⃣ Selecciona el tipo de proyecto (presentación, sitio web, documento o publicación en redes sociales), el número de diapositivas, el idioma y haz clic en "Create Outline".
4️⃣ Revisa el contenido del esquema. Elige un diseño, el método de creación de imágenes, agrega preferencias de estilo y haz clic en "Generate!"
4️⃣ La IA comenzará inmediatamente a crear tu presentación. Puedes editar manualmente las diapositivas, realizar cambios a través del chatbot, animar ilustraciones y crear infografías.
💲 Al registrarte, recibirás 400créditos, suficientes para crear 10 presentaciones. Recuerda que todas las ediciones con IA consumen créditos adicionales (a partir de 10 por edición).
Gamma es una excelente herramienta para estudiar, crear contenido para redes sociales o prototipar sitios web rápidamente.
Más sobre este tema:
🔆Nuestras guías de productividad
🔆Herramientas gratuitas de IA para estudiar
#noticias#Gamma@hiaimediaes
🌎 Gamma-ray bursts are the most energetic explosions in the universe, releasing in seconds as much energy as the Sun emits over its entire 10-billion-year lifespan. They are detected by satellites as brief flashes of gamma radiation, and are thought to result from collapsing massive stars or merging neutron stars. ✨
#space⚡#gamma⚡#astrophysics
👉subscribe Interesting Planet
👉more Channels
🪐 In 2013, the Fermi Gamma-ray Space Telescope detected GRB 130427A, one of the most energetic gamma-ray bursts ever observed, originating from the constellation Leo. This explosion unleashed a gamma-ray photon with an energy of 94 billion electron volts—over 20,000 times more energetic than visible light—demonstrating how gamma-ray bursts can produce some of the most extreme energy events in the universe. ✨
#gamma⚡#gamma-ray-bursts ⚡#space-explosions ⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the galaxy ESO 184-G82, astronomers observed GRB 980425—a gamma-ray burst that was directly linked to a supernova explosion called SN 1998bw. Gamma-ray bursts are intense flashes of the highest-energy light in the universe, and the connection in ESO 184-G82 revealed that some of these powerful bursts are caused when massive stars end their lives in energetic supernovae, giving scientists a rare glimpse into how the most violent stellar deaths can unleash extraordinary cosmic fireworks. ✨
#gamma-ray-bursts ⚡#supernovae⚡#galaxies⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the spiral galaxy NGC 3310, astronomers have observed a rare "gamma-ray burst afterglow," the fading embers following one of the universe’s brightest explosions. This lingering glow, seen in visible light and X-rays, lets scientists track how shockwaves from the original burst plow through space, revealing clues about the powerful forces unleashed when massive stars die. ✨
#gamma-ray-bursts ⚡#strange-cosmic-phenomena ⚡#galaxies⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Some gamma-ray bursts last less than two seconds and are thought to result from the collision of two neutron stars—ultra-dense remnants of massive stars that pack more mass than the Sun into a space the size of a city. In 2017, the galaxy NGC 4993, about 130 million light-years away, was the site of such a collision, allowing astronomers to observe both gamma rays and gravitational waves from the same cosmic event—a rare glimpse into the most violent mergers in the universe. ✨
#gamma-ray ⚡#neutronstar⚡#gravitationalwaves⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the spiral galaxy NGC 4993, scientists observed a gamma-ray burst, GRB 170817A, that arrived just 1.7 seconds after gravitational waves from the merger of two neutron stars—ultra-dense stellar remnants. This remarkable event marked the first time both gravitational waves and a gamma-ray burst were detected from the same source, giving astronomers an unprecedented, multi-messenger view of a cosmic collision. ✨
#gamma⚡#astrophysics⚡#neutronstars⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The galaxy Swift J1644+57, located about 3.9 billion light-years from Earth, produced a gamma-ray burst in 2011 so powerful it was visible across the universe. This extraordinary event happened when a star wandered too close to the galaxy’s central black hole, got torn apart, and unleashed jets of high-energy gamma rays—showing how black holes can create some of the brightest, most dramatic explosions ever observed in space. ✨
#gamma-rays ⚡#blackholes⚡#starburst⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 On August 27, 1998, astronomers detected a remarkable gamma-ray burst from the magnetar SGR 1900+14, located about 20,000 light-years away in the constellation Aquila. This event released more than a thousand times the energy of the Sun in just a fraction of a second, making it one of the brightest gamma-ray flashes ever recorded and proving that magnetars—neutron stars with ultra-strong magnetic fields—can unleash explosions powerful enough to briefly outshine entire galaxies. ✨
#gamma-ray-bursts ⚡#magnetar⚡#cosmic-explosions ⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 2021, astronomers detected a record-breaking gamma-ray burst called GRB 211211A, which defied expectations by lasting over a minute—much longer than most "short" bursts thought to arise from merging neutron stars. Observations with space telescopes revealed this unusually long burst likely came from the merger of two neutron stars in a distant galaxy, showing that cosmic collisions can create gamma-ray explosions with a wider variety of durations and energies than previously believed. ✨
#gamma-ray-bursts ⚡#neutron-stars ⚡#cosmic-explosions ⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In December 2004, the galaxy NGC 1637 in the constellation Eridanus was the source of a rare and powerful cosmic event known as a "short gamma-ray burst." Lasting less than two seconds, these bursts are believed to result from the merger of two neutron stars—ultra-dense remnants of massive stars—which create a flash of high-energy gamma rays strong enough to briefly outshine entire galaxies before fading away in moments. ✨
#gamma-rays ⚡#neutron-stars ⚡#cosmic-explosions ⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels