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

Резултати

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

Пребарај: #highpressure

当前筛选 #highpressure清除筛选
American Оbserver

@american_observer · Post #5567 · 05.04.2026 г., 02:04

🔤🔤🔤🔤➖ Over the last few days, high water temperatures have cooled somewhat, raising the prospect that the heatwave may be dissipating already. It will take more time, however, to know for sure that the heat is clearing. “The expectation right now is that likely the waters down to even southern California should start cooling a little bit into next month, but it’s not a guaranteed thing,” Leising said. “The concern is the sequence of events and how they unfold.” Prolonged ocean heat has a devastating impact on phytoplankton and can cause harmful algal blooms. Those changes can wreak havoc on many forms of marine life, from sea lions and dolphins, to shore birds and halibut. The Blob years led to one of the worst Dungeness crab seasons in recent history, said Melissa Carter, a researcher at the UC-San Diego Scripps Institution of Oceanography. Such heatwaves are becoming more common and lasting longer, partly because of the slow warming of the oceans driven by the climate crisis, and partly because of atmospheric changes that scientists are still struggling to understand. “The question is what’s causing us to have these extreme warm temperatures?” Carter said. “What are the drivers? That’s what we’re trying to find out.” What concerns Carter is that once these high-pressure systems establish themselves in an area, they create a “feedback loop” that tends to reinforce warm, calm conditions, making upwelling less likely to occur, she said. “If these systems do become that strong and persistent, where they come every year, it can have the potential to shut down upwelling,” Carter said. “Everything we think of related to the health of the ecosystems of the west coast could be forever altered.” The lingering ocean heat offers a few upsides, though they pale in comparison with the costs. The warmer water temperatures bring tuna far closer to shore, making it easier to fish for them. Surfers and swimmers have also enjoyed warmer water through the winter. “I enjoy being in the water when it’s a marine heatwave,” Carter said. “But our ocean should not be a swimming pool. Nothing can live in a swimming pool. That’s not what we want.” #highpressure#conditions#marine#life#ocean 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5566 · 05.04.2026 г., 01:02

Researchers Warn the High-Pressure Conditions Could Disrupt Marine Life 🔤🔤🔤🔤1️⃣ For more than a century, shoreline stations operated by the Scripps Institution of Oceanography have measured water temperatures along the California coast. This year, they are flashing a warning sign. Over the last three months, several stations have repeatedly posted record-breaking daily high temperatures – with the La Jolla station registering temperatures a full 10F above historical average at one point last month. The waters of southern California historically warm every few years as tropical currents make their way north, a phenomenon known as El Niño. But the marine heatwave that started last fall wasn’t caused by tropical currents. Instead, a high-pressure atmospheric system – think of calm, sunny days – has perched above southern California, warming both air and sea above historic levels. The same phenomenon has helped fuel a ferocious California heatwave on land. Testing the waters: can pumping chemicals into the ocean help stop global heating? The extended ocean warming has drawn comparisons to “the Blob”, a three-year marine heatwave caused by similar prolonged high-pressure conditions a decade ago that devastated marine life. The next few weeks are likely to determine whether this marine heatwave fizzles out or evolves into something more Blob-like, scientists say. “The biggest concern is how the year plays out,” Andrew Leising, an oceanographer with the National Oceanic and Atmospheric Administration, said. “We could be looking at much larger impacts next fall and winter, if it stays warm and then it’s followed by a strong El Niño.” It’s typical in the spring for shifting atmospheric conditions to generate north-westerly winds that push warm surface water back out to the open ocean, allowing cooler water from below to rise to the surface–a phenomenon called upwelling. Upwelling brings nutrient-rich water from the depths to the surface, feeding the phytoplankton that play a crucial role in supporting much of California’s marine life. #highpressure#conditions#marine#life#ocean 📱American Оbserver - Stay up to date on all important events 🇺🇸